Skip to content

Fix #23 Add Hosted MCP server tool support #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/wild-stars-teach.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@openai/agents-openai': patch
'@openai/agents-core': patch
---

Add hosted MCP server support
86 changes: 86 additions & 0 deletions examples/mcp/hosted-mcp-human-in-the-loop.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import * as readline from 'readline/promises';
import { stdin, stdout } from 'node:process';
import { Agent, run, hostedMcpTool, RunToolApprovalItem } from '@openai/agents';

async function promptApproval(item: RunToolApprovalItem): Promise<boolean> {
const rl = readline.createInterface({ input: stdin, output: stdout });
const name = item.rawItem.name;
const params = JSON.parse(item.rawItem.providerData?.arguments || '{}');
const answer = await rl.question(
`Approve running tool (mcp: ${name}, params: ${JSON.stringify(params)})? (y/n) `,
);
rl.close();
return answer.toLowerCase().trim() === 'y';
}

async function main(verbose: boolean, stream: boolean): Promise<void> {
// 'always' |
// 'never' |
// { never?: { toolNames: string[] }; always?: { toolNames: string[] } }
const requireApproval = {
never: { toolNames: ['search_codex_code', 'fetch_codex_documentation'] },
always: { toolNames: ['fetch_generic_url_content'] },
};
const agent = new Agent({
name: 'MCP Assistant',
instructions: 'You must always use the MCP tools to answer questions.',
tools: [
hostedMcpTool({
serverLabel: 'gitmcp',
serverUrl: 'https://gitmcp.io/openai/codex',
requireApproval,
// when you don't pass onApproval, the agent loop will handle the approval process
}),
],
});

const input = 'Which language is this repo written in?';

if (stream) {
// Streaming
const result = await run(agent, input, { stream: true, maxTurns: 100 });
for await (const event of result) {
if (verbose) {
console.log(JSON.stringify(event, null, 2));
} else {
if (
event.type === 'raw_model_stream_event' &&
event.data.type === 'model'
) {
console.log(event.data.event.type);
}
}
}
console.log(`Done streaming; final result: ${result.finalOutput}`);
} else {
// Non-streaming
let result = await run(agent, input, { maxTurns: 100 });
while (result.interruptions && result.interruptions.length) {
for (const interruption of result.interruptions) {
const approval = await promptApproval(interruption);
if (approval) {
result.state.approve(interruption);
} else {
result.state.reject(interruption);
}
}
result = await run(agent, result.state, { maxTurns: 100 });
}
console.log(result.finalOutput);

if (verbose) {
console.log('----------------------------------------------------------');
console.log(JSON.stringify(result.newItems, null, 2));
console.log('----------------------------------------------------------');
}
}
}

const args = process.argv.slice(2);
const verbose = args.includes('--verbose');
const stream = args.includes('--stream');

main(verbose, stream).catch((err) => {
console.error(err);
process.exit(1);
});
85 changes: 85 additions & 0 deletions examples/mcp/hosted-mcp-on-approval.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import * as readline from 'readline/promises';
import { stdin, stdout } from 'node:process';
import { Agent, run, hostedMcpTool, RunToolApprovalItem } from '@openai/agents';

async function promptApproval(item: RunToolApprovalItem): Promise<boolean> {
const rl = readline.createInterface({ input: stdin, output: stdout });
const name = item.rawItem.name;
const params = JSON.parse(item.rawItem.providerData?.arguments || '{}');
const answer = await rl.question(
`Approve running tool (mcp: ${name}, params: ${JSON.stringify(params)})? (y/n) `,
);
rl.close();
return answer.toLowerCase().trim() === 'y';
}

async function main(verbose: boolean, stream: boolean): Promise<void> {
// 'always' |
// 'never' |
// { never?: { toolNames: string[] }; always?: { toolNames: string[] } }
const requireApproval = {
never: {
toolNames: ['fetch_codex_documentation', 'fetch_generic_url_content'],
},
always: {
toolNames: ['search_codex_code'],
},
};
const agent = new Agent({
name: 'MCP Assistant',
instructions: 'You must always use the MCP tools to answer questions.',
tools: [
hostedMcpTool({
serverLabel: 'gitmcp',
serverUrl: 'https://gitmcp.io/openai/codex',
requireApproval,
onApproval: async (_context, item) => {
const approval = await promptApproval(item);
return { approve: approval, reason: undefined };
},
}),
],
});

const input = 'Which language is this repo written in?';

if (stream) {
// Streaming
const result = await run(agent, input, { stream: true });
for await (const event of result) {
if (verbose) {
console.log(JSON.stringify(event, null, 2));
} else {
if (
event.type === 'raw_model_stream_event' &&
event.data.type === 'model'
) {
console.log(event.data.event.type);
}
}
}
console.log(`Done streaming; final result: ${result.finalOutput}`);
} else {
// Non-streaming
let result = await run(agent, input);
while (result.interruptions && result.interruptions.length) {
result = await run(agent, result.state);
}
console.log(result.finalOutput);

if (verbose) {
console.log('----------------------------------------------------------');
console.log(JSON.stringify(result.newItems, null, 2));
console.log('----------------------------------------------------------');
}
}
}

const args = process.argv.slice(2);
const verbose = args.includes('--verbose');
const stream = args.includes('--stream');

main(verbose, stream).catch((err) => {
console.error(err);
process.exit(1);
});
55 changes: 55 additions & 0 deletions examples/mcp/hosted-mcp-simple.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Agent, run, hostedMcpTool, withTrace } from '@openai/agents';

async function main(verbose: boolean, stream: boolean): Promise<void> {
withTrace('Hosted MCP Example', async () => {
const agent = new Agent({
name: 'MCP Assistant',
instructions: 'You must always use the MCP tools to answer questions.',
tools: [
hostedMcpTool({
serverLabel: 'gitmcp',
serverUrl: 'https://gitmcp.io/openai/codex',
requireApproval: 'never',
}),
],
});

const input =
'Which language is the repo I pointed in the MCP tool settings written in?';
if (stream) {
const result = await run(agent, input, { stream: true });
for await (const event of result) {
if (
event.type === 'raw_model_stream_event' &&
event.data.type === 'model' &&
event.data.event.type !== 'response.mcp_call_arguments.delta' &&
event.data.event.type !== 'response.output_text.delta'
) {
console.log(`Got event of type ${JSON.stringify(event.data)}`);
}
}
for (const item of result.newItems) {
console.log(JSON.stringify(item, null, 2));
}
console.log(`Done streaming; final result: ${result.finalOutput}`);
} else {
const res = await run(agent, input);
// The repository is primarily written in multiple languages, including Rust and TypeScript...
if (verbose) {
for (const item of res.output) {
console.log(JSON.stringify(item, null, 2));
}
}
console.log(res.finalOutput);
}
});
}

const args = process.argv.slice(2);
const verbose = args.includes('--verbose');
const stream = args.includes('--stream');

main(verbose, stream).catch((err) => {
console.error(err);
process.exit(1);
});
5 changes: 4 additions & 1 deletion examples/mcp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
},
"scripts": {
"build-check": "tsc --noEmit",
"start:stdio": "tsx filesystem-example.ts"
"start:stdio": "tsx filesystem-example.ts",
"start:hosted-mcp-on-approval": "tsx hosted-mcp-on-approval.ts",
"start:hosted-mcp-human-in-the-loop": "tsx hosted-mcp-human-in-the-loop.ts",
"start:hosted-mcp-simple": "tsx hosted-mcp-simple.ts"
}
}
2 changes: 2 additions & 0 deletions packages/agents-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ export {
HostedTool,
ComputerTool,
computerTool,
HostedMCPTool,
hostedMcpTool,
FunctionTool,
FunctionToolResult,
Tool,
Expand Down
2 changes: 1 addition & 1 deletion packages/agents-core/src/items.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ export class RunToolApprovalItem extends RunItemBase {
public readonly type = 'tool_approval_item' as const;

constructor(
public rawItem: protocol.FunctionCallItem,
public rawItem: protocol.FunctionCallItem | protocol.HostedToolCallItem,
public agent: Agent<any, any>,
) {
super();
Expand Down
14 changes: 12 additions & 2 deletions packages/agents-core/src/runContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,12 @@ export class RunContext<TContext = UnknownContext> {
rejected: [],
};
if (Array.isArray(approvalEntry.approved)) {
approvalEntry.approved.push(approvalItem.rawItem.callId);
// function tool has call_id, hosted tool call has id
const callId =
'callId' in approvalItem.rawItem
? approvalItem.rawItem.callId // function tools
: approvalItem.rawItem.id!; // hosted tools
approvalEntry.approved.push(callId);
}
this.#approvals.set(toolName, approvalEntry);
}
Expand Down Expand Up @@ -146,7 +151,12 @@ export class RunContext<TContext = UnknownContext> {
};

if (Array.isArray(approvalEntry.rejected)) {
approvalEntry.rejected.push(approvalItem.rawItem.callId);
// function tool has call_id, hosted tool call has id
const callId =
'callId' in approvalItem.rawItem
? approvalItem.rawItem.callId // function tools
: approvalItem.rawItem.id!; // hosted tools
approvalEntry.rejected.push(callId);
}
this.#approvals.set(toolName, approvalEntry);
}
Expand Down
Loading