# How to integrate D2lbrightspace MCP with Pydantic AI

```json
{
  "title": "How to integrate D2lbrightspace MCP with Pydantic AI",
  "toolkit": "D2lbrightspace",
  "toolkit_slug": "d2lbrightspace",
  "framework": "Pydantic AI",
  "framework_slug": "pydantic-ai",
  "url": "https://composio.dev/toolkits/d2lbrightspace/framework/pydantic-ai",
  "markdown_url": "https://composio.dev/toolkits/d2lbrightspace/framework/pydantic-ai.md",
  "updated_at": "2026-05-12T10:08:09.158Z"
}
```

## Introduction

This guide walks you through connecting D2lbrightspace to Pydantic AI using the Composio tool router. By the end, you'll have a working D2lbrightspace agent that can create a new quiz for your math course, add a new user to the spring semester, copy an instructor role for a new department through natural language commands.
This guide will help you understand how to give your Pydantic AI agent real control over a D2lbrightspace account through Composio's D2lbrightspace MCP server.
Before we dive in, let's take a quick look at the key ideas and tools involved.

## Also integrate D2lbrightspace with

- [OpenAI Agents SDK](https://composio.dev/toolkits/d2lbrightspace/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/d2lbrightspace/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/d2lbrightspace/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/d2lbrightspace/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/d2lbrightspace/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/d2lbrightspace/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/d2lbrightspace/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/d2lbrightspace/framework/cli)
- [Google ADK](https://composio.dev/toolkits/d2lbrightspace/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/d2lbrightspace/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/d2lbrightspace/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/d2lbrightspace/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/d2lbrightspace/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/d2lbrightspace/framework/crew-ai)

## TL;DR

Here's what you'll learn:
- How to set up your Composio API key and User ID
- How to create a Composio Tool Router session for D2lbrightspace
- How to attach an MCP Server to a Pydantic AI agent
- How to stream responses and maintain chat history
- How to build a simple REPL-style chat interface to test your D2lbrightspace workflows

## What is Pydantic AI?

Pydantic AI is a Python framework for building AI agents with strong typing and validation. It leverages Pydantic's data validation capabilities to create robust, type-safe AI applications.
Key features include:
- Type Safety: Built on Pydantic for automatic data validation
- MCP Support: Native support for Model Context Protocol servers
- Streaming: Built-in support for streaming responses
- Async First: Designed for async/await patterns

## What is the D2lbrightspace MCP server, and what's possible with it?

The D2lbrightspace MCP server is an implementation of the Model Context Protocol that connects your AI agent and assistants like Claude, Cursor, etc directly to your D2L Brightspace account. It provides structured and secure access to your LMS, so your agent can perform actions like creating courses, managing quizzes, handling user enrollment, and automating gradebook operations on your behalf.
- Automated course creation and management: Instantly create new courses, course offerings, or templates, and streamline updates or deletions without manual intervention.
- Quiz and assessment automation: Let your agent set up new quizzes, organize quiz categories, and configure assessment parameters to enhance the learning experience.
- Gradebook and feedback management: Effortlessly create, modify, or delete grade objects to keep your course grading up to date and provide prompt feedback to learners.
- User enrollment and management: Create new user accounts, manage user roles, and handle enrollment or impersonation tasks to simplify onboarding and administration.
- Role and permissions control: Copy existing roles, adjust specific permissions, and fine-tune access for different user groups—all directly through your agent.

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `D2LBRIGHTSPACE_COPY_ROLE` | Copy Role | Creates a new role copied from an existing role in D2L Brightspace. Notes: - The new role will not have any capabilities upon the old role from which it was created - Some capabilities will be copied for the new role (e.g., if old role users could impersonate other old role users, new role users will be able to impersonate other new role users) - Additional capabilities must be manually created after copying Requires OAuth2 scope: - role:detail:create Available in API versions unstable (LMS v10.4.10+) |
| `D2LBRIGHTSPACE_CREATE_A_COURSE_OFFERING` | Create Course Offering | Creates a new course offering in D2L Brightspace. Notes: - Course code limitations: max 50 chars, no special chars: \ : * ? " \| ' # , % & - Path: leave empty if path enforcement is enabled - SemesterId: provide null if not using the Semester element - CanSelfRegister: required for API v1.28+, not supported before v1.28 Requires OAuth2 scope: - orgunits:course:create Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_CREATE_A_COURSE_TEMPLATE` | Create Course Template | Creates a new course template in D2L Brightspace. Notes: - Course template code limitations: max 50 chars, no special chars: \ : * ? " \| ' # , % & - Path: leave empty if path enforcement is enabled Requires OAuth2 scope: - orgunits:coursetemplate:create Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_CREATE_GRADE_OBJECT` | Create Grade Object | Creates a new grade object for a particular org unit. The grade object can be one of four types: 1. Numeric: For numeric grades with max points 2. PassFail: For pass/fail assessments 3. SelectBox: For predefined grade options 4. Text: For text-only feedback Returns a GradeObject JSON block containing the created grade object's data, including its assigned ID. Requires OAuth2 scope: - grades:gradeobjects:write Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_CREATE_QUIZ` | Create Quiz | Creates a new quiz in D2L Brightspace. Notes: - NumberOfAttemptsAllowed must be between 1 and 10 (inclusive) or null for unlimited - Password must not be empty or whitespace if provided - NotificationEmail must be a valid email address if provided - TimeLimitValue: 0 for no limit (with IsEnforced false), or 1-9999 for enforced limit - DeductionPercentage must be between 0 and 100 if provided - As of LE API v1.71: - LateLimitMinutes is ignored - LateSubmissionOption 1 is treated as 2 (AutoSubmitAttempt) - SubmissionGracePeriod is not used - PagingTypeId added in LE API v1.78 - Date fields should be in UTC format Requires OAuth2 scopes: - quizzing:quizzes:read - quizzing:quizzes:create Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_CREATE_QUIZ_CATEGORY` | Create Quiz Category | Creates a new quiz category in D2L Brightspace. Returns a QuizCategoryReadData JSON block containing: - CategoryId: The ID of the created category - Name: The name of the category - SortOrder: The sort order value Requires OAuth2 scopes: - quizzing:quizzes:read - quizzing:quizzes:create Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_CREATE_USER` | Create User | Creates a new user entity in D2L Brightspace. Requires OAuth2 scope: - users:userdata:create Available in API versions 1.46+ (LMS v20.24.3+) Notes: - FirstName and LastName are used as legal names - ExternalEmail must be null or a valid email address - OrgDefinedId must be unique across the organization if provided - Preferred names must be set separately after user creation |
| `D2LBRIGHTSPACE_DELETE_A_COURSE_TEMPLATE` | Delete Course Template | Deletes a course template from D2L Brightspace. Requires OAuth2 scope: - orgunits:course:delete Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_DELETE_COURSE` | Delete Course | Deletes a course offering from D2L Brightspace. Requires OAuth2 scope: - orgunits:course:delete Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_DELETE_GRADE_OBJECT` | Delete Grade Object | Deletes a specific grade object from an org unit. Requires OAuth2 scope: - grades:gradeobjects:delete Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_DELETE_QUIZ` | Delete Quiz | Deletes a quiz from D2L Brightspace. Requires OAuth2 scope: - quizzing:quizzes:delete Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_DELETE_QUIZ_CATEGORY` | Delete Quiz Category | Deletes a quiz category from D2L Brightspace. Requires OAuth2 scope: - quizzing:quizzes:delete Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_DELETE_USER` | Delete User | Deletes a user entity from D2L Brightspace. Requires OAuth2 scope: - users:userdata:delete Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_DELETE_USER_DEMOGRAPHICS` | Delete User Demographics | Deletes one or more of a particular user's associated demographics entries. Notes: - If entry_ids are provided, only those specific entries will be deleted - If entry_ids are not provided, all demographics entries for the user will be deleted Requires OAuth2 scope: - demographics:user:delete Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_A_COURSE_OFFERING` | Get Course Offering | Retrieves a specific course offering from D2L Brightspace. Returns a CourseOffering JSON block with the course's information. Requires OAuth2 scope: - orgunits:course:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_A_COURSE_TEMPLATE` | Get Course Template | Retrieves a course template from D2L Brightspace. Returns a CourseTemplate JSON block with the template's information. Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_COURSE_SCHEMA` | Get Course Schema | Retrieves the list of parent org unit type constraints for course offerings. Returns a JSON array of SchemaElement blocks defining the allowed parent organizational unit types for courses. Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_COURSE_TEMPLATE_SCHEMA` | Get Course Template Schema | Retrieves the list of parent org unit type constraints for course offerings built on this template. Returns a JSON array of SchemaElement blocks defining the allowed parent organizational unit types for course templates. Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_CURRENT_USER` | Get Current User Information | Retrieves the current user context's user information from D2L Brightspace. Requires one of these OAuth2 scopes: - users:profile:read - users:own_profile:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_ENROLLED_ROLES` | Get Enrolled Roles | Retrieves a list of all enrolled user roles the calling user can view in an org unit. Returns a JSON array of Role data blocks containing the properties of all user roles that the calling user context has permission to view and that are currently enrolled in the provided org unit. Requires OAuth2 scope: - role:detail:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_GRADE_ACCESS` | Get Grade Access | Retrieves a list of users with access to a specified grade. Returns an ObjectListPage containing UserAccess blocks. Can optionally filter by specific user ID or role ID. Requires OAuth2 scope: - grades:access:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_GRADE_OBJECT` | Get Grade Object | Retrieves a specific grade object for a particular org unit. Returns a GradeObject JSON block containing the grade object's properties. Requires OAuth2 scope: - grades:gradeobjects:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_GRADE_OBJECTS` | Get Grade Objects | Retrieves all current grade objects for a particular org unit. Returns an array of grade objects. Requires OAuth2 scope: - grades:gradeobjects:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_GRADE_SETUP` | Get Grade Setup | Retrieves the grades configuration for an org unit. Returns a GradeSetupInfo JSON block containing the grades setup information. Requires OAuth2 scope: - grades:gradesettings:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_GRADE_STATISTICS` | Get Grade Statistics | Retrieves statistics for a specified grade item. Returns a GradeStatisticsInfo JSON block containing statistical data about the grade item. Requires OAuth2 scope: - grades:gradestatistics:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_ORG_UNIT_DEMOGRAPHICS` | Get Org Unit Demographics | Retrieves all demographics entries for users enrolled in a particular org unit. Notes: - Filters are applied cumulatively (all conditions must match) - When using ID lists in filters, matching any ID in the list satisfies that filter - For example: with roleIds=[1,2], userIds=[3,4], search="value": * Users must have role 1 OR 2 (either role matches) * AND must have ID 3 OR 4 (either ID matches) * AND must have a field matching "value" - Results are paged; use bookmark parameter for subsequent pages Requires OAuth2 scope: - demographics:orgunit:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_QUIZ` | Get Quiz | Retrieves a specific quiz from an org unit. Returns a QuizReadData JSON block containing the quiz's properties. Requires OAuth2 scope: - quizzing:quizzes:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_ACCESS` | Get Quiz Access | Retrieves a list of users with access to a specified quiz. Returns an ObjectListPage JSON block containing a list of UserAccess blocks. Can filter by specific user ID or role ID. Requires OAuth2 scope: - quizzing:access:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_ATTEMPT` | Get Quiz Attempt | Retrieves a specific quiz attempt. Returns a QuizAttemptData JSON block containing the attempt's properties. Requires OAuth2 scope: - quizzing:attempts:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_ATTEMPTS` | Get Quiz Attempts | Retrieves a list of attempts for a quiz. Can optionally filter attempts for a specific user. Returns an ObjectListPage JSON block containing a list of QuizAttemptData blocks. Requires OAuth2 scope: - quizzing:attempts:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_CATEGORIES` | Get Quiz Categories | Retrieves all quiz categories belonging to an org unit. Returns an ObjectListPage JSON block containing a list of QuizCategoryReadData blocks. Requires OAuth2 scope: - quizzing:quizzes:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_CATEGORY` | Get Quiz Category | Retrieves a specific quiz category from an org unit. Returns a QuizCategoryReadData JSON block containing the category's properties. Requires OAuth2 scope: - quizzing:quizzes:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZ_QUESTIONS` | Get Quiz Questions | Retrieves all questions in a quiz. Returns an ObjectListPage JSON block containing a list of QuestionData blocks. Requires OAuth2 scope: - quizzing:quizzes:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_QUIZZES` | Get Quizzes | Retrieves all quizzes belonging to an org unit. Returns an ObjectListPage JSON block containing a list of QuizReadData blocks. Requires OAuth2 scope: - quizzing:quizzes:read Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_GET_ROLE_BY_ID` | Get Role by ID | Retrieves a particular user role from D2L Brightspace by its ID. Requires OAuth2 scope: - role:detail:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_ROLES` | Get Roles | Retrieves a list of all known user roles in D2L Brightspace. Returns a list of Role data blocks containing the properties of all user roles that the calling user context has permission to manage. Requires OAuth2 scope: - role:detail:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_USER_BY_ID` | Get User by ID | Retrieves data for a particular user from D2L Brightspace. Requires OAuth2 scope: - users:userdata:read Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_GET_USERS` | Get Users | Retrieves data for one or more users from D2L Brightspace. Requires OAuth2 scope: - users:userdata:read Available in API versions 1.46+ (LMS v20.24.3+) Notes: - All search parameters (orgDefinedId, userName, externalEmail) are optional - Returns paginated results when using bookmark parameter |
| `D2LBRIGHTSPACE_UPDATE_A_COURSE_OFFERING` | Update Course Offering | Updates an existing course offering in D2L Brightspace. Notes: - Course code limitations: max 50 chars, no special chars: \ : * ? " \| ' # , % & - StartDate/EndDate: null values won't overwrite existing dates - CanSelfRegister: required for API v1.27+, not supported before v1.27 - Description: ignored in API versions 1.25 and earlier Requires OAuth2 scope: - orgunits:course:update Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_UPDATE_A_COURSE_TEMPLATE` | Update Course Template | Updates an existing course template in D2L Brightspace. Notes: - This action completely replaces the template's data with the provided values - Course template code limitations: max 50 chars, no special chars: \ : * ? " \| ' # , % & Available in API versions 1.46+ (LMS v20.24.3+) |
| `D2LBRIGHTSPACE_UPDATE_GRADE_OBJECT` | Update Grade Object | Updates a specific grade object. The grade object can be one of four types: 1. Numeric: For numeric grades with max points 2. PassFail: For pass/fail assessments 3. SelectBox: For predefined grade options 4. Text: For text-only feedback Note: The provided data completely replaces the existing grade object's data. Returns a GradeObject JSON block containing the updated grade object's data. Requires OAuth2 scope: - grades:gradeobjects:write Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_UPDATE_GRADE_SETUP` | Update Grade Setup | Updates the grades configuration for an org unit. Expects a GradeSetupInfo JSON block containing: - GradingSystem: The grading system type - IsNullGradeZero: Whether null grades should be treated as zero - DefaultGradeSchemeId: ID of the default grade scheme Returns the updated GradeSetupInfo JSON block. Requires OAuth2 scope: - grades:gradesettings:write Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_UPDATE_QUIZ` | Update Quiz | Updates an existing quiz in D2L Brightspace. Notes: - This action updates only the provided quiz properties - NumberOfAttemptsAllowed must be between 1 and 10 (inclusive) or null for unlimited - Password must not be empty or whitespace if provided - NotificationEmail must be a valid email address if provided - TimeLimitValue: 0 for no limit (with IsEnforced false), or 1-9999 for enforced limit - DeductionPercentage must be between 0 and 100 if provided - Cannot restrict shared quizzes for special access - Cannot set auto-submit for quizzes with mandatory questions - As of LE API v1.71: - LateLimitMinutes is ignored - LateSubmissionOption 1 is treated as 2 (AutoSubmitAttempt) - SubmissionGracePeriod is not used - PagingTypeId added in LE API v1.78 - Date fields should be in UTC format Requires OAuth2 scopes: - quizzing:quizzes:read - quizzing:quizzes:write Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_UPDATE_QUIZ_CATEGORY` | Update Quiz Category | Updates an existing quiz category in D2L Brightspace. Returns a QuizCategoryReadData JSON block containing: - CategoryId: The ID of the category - Name: The name of the category - SortOrder: The sort order value Requires OAuth2 scopes: - quizzing:quizzes:read - quizzing:quizzes:write Available in API versions 1.75+ (LMS v20.24.5+) |
| `D2LBRIGHTSPACE_UPDATE_USER` | Update User | Updates an existing user entity in D2L Brightspace. Requires OAuth2 scope: - users:userdata:update Available in API versions 1.46+ (LMS v20.24.3+) Notes: - FirstName and LastName update preferred names if set, otherwise update legal names - ExternalEmail must be null or a valid email address - OrgDefinedId must be unique across the organization if provided - Pronouns: use empty string ("") to reset, null to keep existing value |

## Supported Triggers

None listed.

## Creating MCP Server - Stand-alone vs Composio SDK

The D2lbrightspace MCP server is an implementation of the Model Context Protocol that connects your AI agent to D2lbrightspace. It provides structured and secure access so your agent can perform D2lbrightspace operations on your behalf through a secure, permission-based interface.
With Composio's managed implementation, you don't have to create your own developer app. For production, if you're building an end product, we recommend using your own credentials. The managed server helps you prototype fast and go from 0-1 faster.

## Step-by-step Guide

### 1. Prerequisites

Before starting, make sure you have:
- Python 3.9 or higher
- A Composio account with an active API key
- Basic familiarity with Python and async programming

### 1. Getting API Keys for OpenAI and Composio

OpenAI API Key
- Go to the [OpenAI dashboard](https://platform.openai.com/settings/organization/api-keys) and create an API key. You'll need credits to use the models, or you can connect to another model provider.
- Keep the API key safe.
Composio API Key
- Log in to the [Composio dashboard](https://dashboard.composio.dev?utm_source=toolkits&utm_medium=framework_docs).
- Navigate to your API settings and generate a new API key.
- Store this key securely as you'll need it for authentication.

### 2. Install dependencies

Install the required libraries.
What's happening:
- composio connects your agent to external SaaS tools like D2lbrightspace
- pydantic-ai lets you create structured AI agents with tool support
- python-dotenv loads your environment variables securely from a .env file
```bash
pip install composio pydantic-ai python-dotenv
```

### 3. Set up environment variables

Create a .env file in your project root.
What's happening:
- COMPOSIO_API_KEY authenticates your agent to Composio's API
- USER_ID associates your session with your account for secure tool access
- OPENAI_API_KEY to access OpenAI LLMs
```bash
COMPOSIO_API_KEY=your_composio_api_key_here
USER_ID=your_user_id_here
OPENAI_API_KEY=your_openai_api_key
```

### 4. Import dependencies

What's happening:
- We load environment variables and import required modules
- Composio manages connections to D2lbrightspace
- MCPServerStreamableHTTP connects to the D2lbrightspace MCP server endpoint
- Agent from Pydantic AI lets you define and run the AI assistant
```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()
```

### 5. Create a Tool Router Session

What's happening:
- We're creating a Tool Router session that gives your agent access to D2lbrightspace tools
- The create method takes the user ID and specifies which toolkits should be available
- The returned session.mcp.url is the MCP server URL that your agent will use
```python
async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for D2lbrightspace
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["d2lbrightspace"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")
```

### 6. Initialize the Pydantic AI Agent

What's happening:
- The MCP client connects to the D2lbrightspace endpoint
- The agent uses GPT-5 to interpret user commands and perform D2lbrightspace operations
- The instructions field defines the agent's role and behavior
```python
# Attach the MCP server to a Pydantic AI Agent
d2lbrightspace_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
agent = Agent(
    "openai:gpt-5",
    toolsets=[d2lbrightspace_mcp],
    instructions=(
        "You are a D2lbrightspace assistant. Use D2lbrightspace tools to help users "
        "with their requests. Ask clarifying questions when needed."
    ),
)
```

### 7. Build the chat interface

What's happening:
- The agent reads input from the terminal and streams its response
- D2lbrightspace API calls happen automatically under the hood
- The model keeps conversation history to maintain context across turns
```python
# Simple REPL with message history
history = []
print("Chat started! Type 'exit' or 'quit' to end.\n")
print("Try asking the agent to help you with D2lbrightspace.\n")

while True:
    user_input = input("You: ").strip()
    if user_input.lower() in {"exit", "quit", "bye"}:
        print("\nGoodbye!")
        break
    if not user_input:
        continue

    print("\nAgent is thinking...\n", flush=True)

    async with agent.run_stream(user_input, message_history=history) as stream_result:
        collected_text = ""
        async for chunk in stream_result.stream_output():
            text_piece = None
            if isinstance(chunk, str):
                text_piece = chunk
            elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                text_piece = chunk.delta
            elif hasattr(chunk, "text"):
                text_piece = chunk.text
            if text_piece:
                collected_text += text_piece
        result = stream_result

    print(f"Agent: {collected_text}\n")
    history = result.all_messages()
```

### 8. Run the application

What's happening:
- The asyncio loop launches the agent and keeps it running until you exit
```python
if __name__ == "__main__":
    asyncio.run(main())
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv
from composio import Composio
from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStreamableHTTP

load_dotenv()

async def main():
    api_key = os.getenv("COMPOSIO_API_KEY")
    user_id = os.getenv("USER_ID")
    if not api_key or not user_id:
        raise RuntimeError("Set COMPOSIO_API_KEY and USER_ID in your environment")

    # Create a Composio Tool Router session for D2lbrightspace
    composio = Composio(api_key=api_key)
    session = composio.create(
        user_id=user_id,
        toolkits=["d2lbrightspace"],
    )
    url = session.mcp.url
    if not url:
        raise ValueError("Composio session did not return an MCP URL")

    # Attach the MCP server to a Pydantic AI Agent
    d2lbrightspace_mcp = MCPServerStreamableHTTP(url, headers={"x-api-key": COMPOSIO_API_KEY})
    agent = Agent(
        "openai:gpt-5",
        toolsets=[d2lbrightspace_mcp],
        instructions=(
            "You are a D2lbrightspace assistant. Use D2lbrightspace tools to help users "
            "with their requests. Ask clarifying questions when needed."
        ),
    )

    # Simple REPL with message history
    history = []
    print("Chat started! Type 'exit' or 'quit' to end.\n")
    print("Try asking the agent to help you with D2lbrightspace.\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "bye"}:
            print("\nGoodbye!")
            break
        if not user_input:
            continue

        print("\nAgent is thinking...\n", flush=True)

        async with agent.run_stream(user_input, message_history=history) as stream_result:
            collected_text = ""
            async for chunk in stream_result.stream_output():
                text_piece = None
                if isinstance(chunk, str):
                    text_piece = chunk
                elif hasattr(chunk, "delta") and isinstance(chunk.delta, str):
                    text_piece = chunk.delta
                elif hasattr(chunk, "text"):
                    text_piece = chunk.text
                if text_piece:
                    collected_text += text_piece
            result = stream_result

        print(f"Agent: {collected_text}\n")
        history = result.all_messages()

if __name__ == "__main__":
    asyncio.run(main())
```

## Conclusion

You've built a Pydantic AI agent that can interact with D2lbrightspace through Composio's Tool Router. With this setup, your agent can perform real D2lbrightspace actions through natural language.
You can extend this further by:
- Adding other toolkits like Gmail, HubSpot, or Salesforce
- Building a web-based chat interface around this agent
- Using multiple MCP endpoints to enable cross-app workflows (for example, Gmail + D2lbrightspace for workflow automation)
This architecture makes your AI agent "agent-native", able to securely use APIs in a unified, composable way without custom integrations.

## How to build D2lbrightspace MCP Agent with another framework

- [OpenAI Agents SDK](https://composio.dev/toolkits/d2lbrightspace/framework/open-ai-agents-sdk)
- [Claude Agent SDK](https://composio.dev/toolkits/d2lbrightspace/framework/claude-agents-sdk)
- [Claude Code](https://composio.dev/toolkits/d2lbrightspace/framework/claude-code)
- [Claude Cowork](https://composio.dev/toolkits/d2lbrightspace/framework/claude-cowork)
- [Codex](https://composio.dev/toolkits/d2lbrightspace/framework/codex)
- [OpenClaw](https://composio.dev/toolkits/d2lbrightspace/framework/openclaw)
- [Hermes](https://composio.dev/toolkits/d2lbrightspace/framework/hermes-agent)
- [CLI](https://composio.dev/toolkits/d2lbrightspace/framework/cli)
- [Google ADK](https://composio.dev/toolkits/d2lbrightspace/framework/google-adk)
- [LangChain](https://composio.dev/toolkits/d2lbrightspace/framework/langchain)
- [Vercel AI SDK](https://composio.dev/toolkits/d2lbrightspace/framework/ai-sdk)
- [Mastra AI](https://composio.dev/toolkits/d2lbrightspace/framework/mastra-ai)
- [LlamaIndex](https://composio.dev/toolkits/d2lbrightspace/framework/llama-index)
- [CrewAI](https://composio.dev/toolkits/d2lbrightspace/framework/crew-ai)

## Related Toolkits

- [Canvas](https://composio.dev/toolkits/canvas) - Canvas is a learning management system for online courses, assignments, grading, and collaboration. It's trusted by educators and students to streamline virtual classrooms and enhance digital learning.
- [Accredible certificates](https://composio.dev/toolkits/accredible_certificates) - Accredible Certificates is a platform for creating and managing digital certificates, badges, and blockchain credentials. It streamlines issuing, tracking, and verifying professional achievements for organizations of any size.
- [Api bible](https://composio.dev/toolkits/api_bible) - API.Bible is a developer platform for Scripture content and passage search. Easily integrate Bible verses and translations into your apps or chatbots.
- [Blackboard](https://composio.dev/toolkits/blackboard) - Blackboard is a digital learning platform for higher education and schools, offering tools to manage courses, track engagement, and deliver interactive content. It helps institutions improve student outcomes through actionable analytics and in-app guidance.
- [Certifier](https://composio.dev/toolkits/certifier) - Certifier is a platform for creating, managing, and issuing digital certificates and credentials. Organizations use it to automate and secure the entire credentialing process.
- [Classmarker](https://composio.dev/toolkits/classmarker) - ClassMarker is a professional online quiz maker for business and education. It provides instant grading, flexible test design, and in-depth reporting.
- [Coassemble](https://composio.dev/toolkits/coassemble) - Coassemble is a flexible platform for building, managing, and delivering online training courses. It helps teams streamline onboarding, upskilling, and ongoing learning for employees or partners.
- [Dictionary api](https://composio.dev/toolkits/dictionary_api) - Dictionary api is the Merriam-Webster API providing rich dictionary and thesaurus data for developers. Instantly access definitions, synonyms, etymologies, and audio pronunciations in your apps.
- [Google Classroom](https://composio.dev/toolkits/google_classroom) - Google Classroom is a free web service for educators and students to manage assignments and communication. It streamlines classroom collaboration and grading, making teaching simpler and more connected.
- [Lessonspace](https://composio.dev/toolkits/lessonspace) - Lessonspace is an online collaborative classroom platform offering video, whiteboards, and real-time interaction for educators and students. It streamlines remote teaching with integrated tools for engagement and communication.
- [Linguapop](https://composio.dev/toolkits/linguapop) - Linguapop is a web platform for administering language placement tests in English, German, Spanish, Italian, and French. It helps schools and organizations efficiently manage multilingual assessments and analyze results.
- [Memberspot](https://composio.dev/toolkits/memberspot) - Memberspot is an online course and video-hosting platform for business learning. It helps teams manage, deliver, and track knowledge efficiently.
- [Membervault](https://composio.dev/toolkits/membervault) - Membervault is a platform for hosting courses, memberships, and digital products in one place. It helps you build stronger relationships with your audience by centralizing digital offers and customer engagement.
- [Gmail](https://composio.dev/toolkits/gmail) - Gmail is Google's email service with powerful spam protection, search, and G Suite integration. It keeps your inbox organized and makes communication fast and reliable.
- [Google Calendar](https://composio.dev/toolkits/googlecalendar) - Google Calendar is a time management service for scheduling meetings, events, and reminders. It streamlines personal and team organization with integrated notifications and sharing options.
- [Google Drive](https://composio.dev/toolkits/googledrive) - Google Drive is a cloud storage platform for uploading, sharing, and collaborating on files. It's perfect for keeping your documents accessible and organized across devices.
- [Outlook](https://composio.dev/toolkits/outlook) - Outlook is Microsoft's email and calendaring platform for unified communications and scheduling. It helps users stay organized with powerful email, contacts, and calendar management.
- [Twitter](https://composio.dev/toolkits/twitter) - Twitter is a social media platform for sharing real-time updates, conversations, and news. Stay connected, informed, and engaged with communities worldwide.
- [Google Sheets](https://composio.dev/toolkits/googlesheets) - Google Sheets is a cloud-based spreadsheet tool for real-time collaboration and data analysis. It lets teams work together from anywhere, updating information instantly.
- [Supabase](https://composio.dev/toolkits/supabase) - Supabase is an open-source backend platform offering scalable Postgres databases, authentication, storage, and real-time APIs. It lets developers build modern apps without managing infrastructure.

## Frequently Asked Questions

### What are the differences in Tool Router MCP and D2lbrightspace MCP?

With a standalone D2lbrightspace MCP server, the agents and LLMs can only access a fixed set of D2lbrightspace tools tied to that server. However, with the Composio Tool Router, agents can dynamically load tools from D2lbrightspace and many other apps based on the task at hand, all through a single MCP endpoint.

### Can I use Tool Router MCP with Pydantic AI?

Yes, you can. Pydantic AI fully supports MCP integration. You get structured tool calling, message history handling, and model orchestration while Tool Router takes care of discovering and serving the right D2lbrightspace tools.

### Can I manage the permissions and scopes for D2lbrightspace while using Tool Router?

Yes, absolutely. You can configure which D2lbrightspace scopes and actions are allowed when connecting your account to Composio. You can also bring your own OAuth credentials or API configuration so you keep full control over what the agent can do.

### How safe is my data with Composio Tool Router?

All sensitive data such as tokens, keys, and configuration is fully encrypted at rest and in transit. Composio is SOC 2 Type 2 compliant and follows strict security practices so your D2lbrightspace data and credentials are handled as safely as possible.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
