# How to integrate D2lbrightspace MCP with OpenAI Agents SDK

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

## Introduction

This guide walks you through connecting D2lbrightspace to the OpenAI Agents SDK 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 OpenAI Agents SDK 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

- [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:
- Get and set up your OpenAI and Composio API keys
- Install the necessary dependencies
- Initialize Composio and create a Tool Router session for D2lbrightspace
- Configure an AI agent that can use D2lbrightspace as a tool
- Run a live chat session where you can ask the agent to perform D2lbrightspace operations

## What is OpenAI Agents SDK?

The OpenAI Agents SDK is a lightweight framework for building AI agents that can use tools and maintain conversation state. It provides a simple interface for creating agents with hosted MCP tool support.
Key features include:
- Hosted MCP Tools: Connect to external services through hosted MCP endpoints
- SQLite Sessions: Persist conversation history across interactions
- Simple API: Clean interface with Agent, Runner, and tool configuration
- Streaming Support: Real-time response streaming for interactive applications

## 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:
- Composio API Key and OpenAI API Key
- Primary know-how of OpenAI Agents SDK
- A live D2lbrightspace project
- Some knowledge of Python or Typescript

### 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).
- Go to Settings and copy your API key.

### 2. Install dependencies

Install the Composio SDK and the OpenAI Agents SDK.
```python
pip install composio_openai_agents openai-agents python-dotenv
```

```typescript
npm install @composio/openai-agents @openai/agents dotenv
```

### 3. Set up environment variables

Create a .env file and add your OpenAI and Composio API keys.
```bash
OPENAI_API_KEY=sk-...your-api-key
COMPOSIO_API_KEY=your-api-key
USER_ID=composio_user@gmail.com
```

### 4. Import dependencies

What's happening:
- You're importing all necessary libraries.
- The Composio and OpenAIAgentsProvider classes are imported to connect your OpenAI agent to Composio tools like D2lbrightspace.
```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';
```

### 5. Set up the Composio instance

No description provided.
```python
load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())
```

```typescript
dotenv.config();

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});
```

### 6. Create a Tool Router session

What is happening:
- You give the Tool Router the user id and the toolkits you want available. Here, it is only d2lbrightspace.
- The router checks the user's D2lbrightspace connection and prepares the MCP endpoint.
- The returned session.mcp.url is the MCP URL that your agent will use to access D2lbrightspace.
- This approach keeps things lightweight and lets the agent request D2lbrightspace tools only when needed during the conversation.
```python
# Create a D2lbrightspace Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["d2lbrightspace"]
)

mcp_url = session.mcp.url
```

```typescript
// Create Tool Router session for D2lbrightspace
const session = await composio.create(userId as string, {
  toolkits: ['d2lbrightspace'],
});
const mcpUrl = session.mcp.url;
```

### 7. Configure the agent

No description provided.
```python
# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access D2lbrightspace. "
        "Help users perform D2lbrightspace operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)
```

```typescript
// Configure agent with MCP tool
const agent = new Agent({
  name: 'Assistant',
  model: 'gpt-5',
  instructions:
    'You are a helpful assistant that can access D2lbrightspace. Help users perform D2lbrightspace operations through natural language.',
  tools: [
    hostedMcpTool({
      serverLabel: 'tool_router',
      serverUrl: mcpUrl,
      headers: { 'x-api-key': composioApiKey },
      requireApproval: 'never',
    }),
  ],
});
```

### 8. Start chat loop and handle conversation

No description provided.
```python
print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
// Keep conversation state across turns
const conversationSession = new OpenAIConversationsSession();

// Simple CLI
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  prompt: 'You: ',
});

console.log('\nComposio Tool Router session created.');
console.log('\nChat started. Type your requests below.');
console.log("Commands: 'exit', 'quit', or 'q' to end\n");

try {
  const first = await run(agent, 'What can you help me with?', { session: conversationSession });
  console.log(`Assistant: ${first.finalOutput}\n`);
} catch (e) {
  console.error('Error:', e instanceof Error ? e.message : e, '\n');
}

rl.prompt();

rl.on('line', async (userInput) => {
  const text = userInput.trim();

  if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
    console.log('Goodbye!');
    rl.close();
    process.exit(0);
  }

  if (!text) {
    rl.prompt();
    return;
  }

  try {
    const result = await run(agent, text, { session: conversationSession });
    console.log(`\nAssistant: ${result.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();
});

rl.on('close', () => {
  console.log('\n👋 Session ended.');
  process.exit(0);
});
```

## Complete Code

```python
import asyncio
import os
from dotenv import load_dotenv

from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
from agents import Agent, Runner, HostedMCPTool, SQLiteSession

load_dotenv()

api_key = os.getenv("COMPOSIO_API_KEY")
user_id = os.getenv("USER_ID")

if not api_key:
    raise RuntimeError("COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key")

# Initialize Composio
composio = Composio(api_key=api_key, provider=OpenAIAgentsProvider())

# Create Tool Router session
session = composio.create(
    user_id=user_id,
    toolkits=["d2lbrightspace"]
)
mcp_url = session.mcp.url

# Configure agent with MCP tool
agent = Agent(
    name="Assistant",
    model="gpt-5",
    instructions=(
        "You are a helpful assistant that can access D2lbrightspace. "
        "Help users perform D2lbrightspace operations through natural language."
    ),
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "tool_router",
                "server_url": mcp_url,
                "headers": {"x-api-key": api_key},
                "require_approval": "never",
            }
        )
    ],
)

print("\nComposio Tool Router session created.")

chat_session = SQLiteSession("conversation_openai_toolrouter")

print("\nChat started. Type your requests below.")
print("Commands: 'exit', 'quit', or 'q' to end\n")

async def main():
    try:
        result = await Runner.run(
            agent,
            "What can you help me with?",
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")
    except Exception as e:
        print(f"Error: {e}\n")

    while True:
        user_input = input("You: ").strip()
        if user_input.lower() in {"exit", "quit", "q"}:
            print("Goodbye!")
            break

        result = await Runner.run(
            agent,
            user_input,
            session=chat_session
        )
        print(f"Assistant: {result.final_output}\n")

asyncio.run(main())
```

```typescript
import 'dotenv/config';
import { Composio } from '@composio/core';
import { OpenAIAgentsProvider } from '@composio/openai-agents';
import { Agent, hostedMcpTool, run, OpenAIConversationsSession } from '@openai/agents';
import * as readline from 'readline';

const composioApiKey = process.env.COMPOSIO_API_KEY;
const userId = process.env.USER_ID;

if (!composioApiKey) {
  throw new Error('COMPOSIO_API_KEY is not set. Create a .env file with COMPOSIO_API_KEY=your_key');
}
if (!userId) {
  throw new Error('USER_ID is not set');
}

// Initialize Composio
const composio = new Composio({
  apiKey: composioApiKey,
  provider: new OpenAIAgentsProvider(),
});

async function main() {
  // Create Tool Router session
  const session = await composio.create(userId as string, {
    toolkits: ['d2lbrightspace'],
  });
  const mcpUrl = session.mcp.url;

  // Configure agent with MCP tool
  const agent = new Agent({
    name: 'Assistant',
    model: 'gpt-5',
    instructions:
      'You are a helpful assistant that can access D2lbrightspace. Help users perform D2lbrightspace operations through natural language.',
    tools: [
      hostedMcpTool({
        serverLabel: 'tool_router',
        serverUrl: mcpUrl,
        headers: { 'x-api-key': composioApiKey },
        requireApproval: 'never',
      }),
    ],
  });

  // Keep conversation state across turns
  const conversationSession = new OpenAIConversationsSession();

  // Simple CLI
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    prompt: 'You: ',
  });

  console.log('\nComposio Tool Router session created.');
  console.log('\nChat started. Type your requests below.');
  console.log("Commands: 'exit', 'quit', or 'q' to end\n");

  try {
    const first = await run(agent, 'What can you help me with?', { session: conversationSession });
    console.log(`Assistant: ${first.finalOutput}\n`);
  } catch (e) {
    console.error('Error:', e instanceof Error ? e.message : e, '\n');
  }

  rl.prompt();

  rl.on('line', async (userInput) => {
    const text = userInput.trim();

    if (['exit', 'quit', 'q'].includes(text.toLowerCase())) {
      console.log('Goodbye!');
      rl.close();
      process.exit(0);
    }

    if (!text) {
      rl.prompt();
      return;
    }

    try {
      const result = await run(agent, text, { session: conversationSession });
      console.log(`\nAssistant: ${result.finalOutput}\n`);
    } catch (e) {
      console.error('Error:', e instanceof Error ? e.message : e, '\n');
    }

    rl.prompt();
  });

  rl.on('close', () => {
    console.log('\nSession ended.');
    process.exit(0);
  });
}

main().catch((err) => {
  console.error('Fatal error:', err);
  process.exit(1);
});
```

## Conclusion

This was a starter code for integrating D2lbrightspace MCP with OpenAI Agents SDK to build a functional AI agent that can interact with D2lbrightspace.
Key features:
- Hosted MCP tool integration through Composio's Tool Router
- SQLite session persistence for conversation history
- Simple async chat loop for interactive testing
You can extend this by adding more toolkits, implementing custom business logic, or building a web interface around the agent.

## How to build D2lbrightspace MCP Agent with another framework

- [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 OpenAI Agents SDK?

Yes, you can. OpenAI Agents SDK 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)
