@openai/agents-core
Version:
The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows.
438 lines (437 loc) • 18 kB
TypeScript
import { FunctionTool, Tool } from './tool';
import { type Span } from './tracing';
import { type Logger } from './logger';
import { JsonObjectSchemaNonStrict, JsonObjectSchemaStrict, UnknownContext } from './types';
import type { MCPToolCustomDataExtractor, MCPToolFilterCallable, MCPToolFilterStatic, MCPToolMetaResolver } from './mcpUtil';
import type { RunContext } from './runContext';
import type { Agent } from './agent';
import { BaseMCPServerSSE, BaseMCPServerStdio, BaseMCPServerStreamableHttp, MCPTool } from './mcpShared';
import type { ToolInputGuardrailDefinition, ToolOutputGuardrailDefinition } from './toolGuardrail';
export { BaseMCPServerSSE, BaseMCPServerStdio, BaseMCPServerStreamableHttp, DEFAULT_SSE_MCP_CLIENT_LOGGER_NAME, DEFAULT_STDIO_MCP_CLIENT_LOGGER_NAME, DEFAULT_STREAMABLE_HTTP_MCP_CLIENT_LOGGER_NAME, MCPTool, attachCallToolResultMetadata, } from './mcpShared';
export { invalidateServerToolsCache } from './mcpToolCache';
export type MCPToolErrorFunction = (args: {
context: RunContext;
error: Error | unknown;
}) => Promise<string> | string;
export interface MCPCallToolOptions {
signal?: AbortSignal;
}
/**
* Interface for MCP server implementations.
* Provides methods for connecting, listing tools, calling tools, and cleanup.
*/
export interface MCPServer {
cacheToolsList: boolean;
toolFilter?: MCPToolFilterCallable | MCPToolFilterStatic;
toolMetaResolver?: MCPToolMetaResolver;
customDataExtractor?: MCPToolCustomDataExtractor;
/** Guardrails applied before every tool on this server is invoked. */
toolInputGuardrails?: ToolInputGuardrailDefinition<any>[];
/** Guardrails applied after every tool on this server returns. */
toolOutputGuardrails?: ToolOutputGuardrailDefinition<any>[];
/**
* Whether to use MCP `structuredContent` as the model-visible tool output when available.
* Defaults to false to preserve the existing content-based output behavior.
*/
useStructuredContent?: boolean;
/**
* Optional function to convert MCP tool failures into model-visible messages.
* Set to null to rethrow errors instead of converting them.
*/
errorFunction?: MCPToolErrorFunction | null;
connect(): Promise<void>;
readonly name: string;
close(): Promise<void>;
listTools(): Promise<MCPTool[]>;
callTool(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResultContent>;
/**
* Invoke a tool and return the full serializable MCP result.
*/
callToolResult?(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResult>;
invalidateToolsCache(): Promise<void>;
}
/**
* Minimal params accepted by MCP resource-listing methods.
*/
export interface MCPListResourcesParams {
cursor?: string;
[key: string]: unknown;
}
/**
* Minimal MCP resource definition used by this SDK.
*/
export interface MCPResource {
uri: string;
name?: string;
title?: string;
description?: string;
mimeType?: string;
size?: number;
annotations?: Record<string, unknown>;
[key: string]: unknown;
}
/**
* Minimal MCP resource template definition used by this SDK.
*/
export interface MCPResourceTemplate {
uriTemplate: string;
name?: string;
title?: string;
description?: string;
mimeType?: string;
annotations?: Record<string, unknown>;
[key: string]: unknown;
}
/**
* Text resource content returned by `readResource`.
*/
export interface MCPTextResourceContent {
uri: string;
mimeType?: string;
text: string;
[key: string]: unknown;
}
/**
* Binary resource content returned by `readResource`.
*/
export interface MCPBlobResourceContent {
uri: string;
mimeType?: string;
blob: string;
[key: string]: unknown;
}
export type MCPResourceContent = MCPTextResourceContent | MCPBlobResourceContent;
/**
* Result returned by `listResources`.
*/
export interface MCPListResourcesResult {
resources: MCPResource[];
nextCursor?: string;
[key: string]: unknown;
}
/**
* Result returned by `listResourceTemplates`.
*/
export interface MCPListResourceTemplatesResult {
resourceTemplates: MCPResourceTemplate[];
nextCursor?: string;
[key: string]: unknown;
}
/**
* Result returned by `readResource`.
*/
export interface MCPReadResourceResult {
contents: MCPResourceContent[];
[key: string]: unknown;
}
/**
* Extended MCP server surface for servers that expose resources.
*/
export interface MCPServerWithResources extends MCPServer {
listResources(params?: MCPListResourcesParams): Promise<MCPListResourcesResult>;
listResourceTemplates(params?: MCPListResourcesParams): Promise<MCPListResourceTemplatesResult>;
readResource(uri: string): Promise<MCPReadResourceResult>;
}
/**
* Public interface of an MCP server that provides tools.
* You can use this class to pass MCP server settings to your agent.
*/
export declare class MCPServerStdio extends BaseMCPServerStdio implements MCPServerWithResources {
private underlying;
private readonly toolsLifecycle;
constructor(options: MCPServerStdioOptions);
get name(): string;
private invalidateToolsCaches;
connect(): Promise<void>;
close(): Promise<void>;
listTools(): Promise<MCPTool[]>;
callTool(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResultContent>;
callToolResult(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResult>;
listResources(params?: MCPListResourcesParams): Promise<MCPListResourcesResult>;
listResourceTemplates(params?: MCPListResourcesParams): Promise<MCPListResourceTemplatesResult>;
readResource(uri: string): Promise<MCPReadResourceResult>;
invalidateToolsCache(): Promise<void>;
}
export declare class MCPServerStreamableHttp extends BaseMCPServerStreamableHttp implements MCPServerWithResources {
private underlying;
private _cachedToolsSessionId;
private readonly toolsLifecycle;
constructor(options: MCPServerStreamableHttpOptions);
private clearLocalToolsCache;
private invalidateToolsCaches;
get name(): string;
get sessionId(): string | undefined;
connect(): Promise<void>;
close(): Promise<void>;
listTools(): Promise<MCPTool[]>;
callTool(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResultContent>;
callToolResult(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResult>;
listResources(params?: MCPListResourcesParams): Promise<MCPListResourcesResult>;
listResourceTemplates(params?: MCPListResourcesParams): Promise<MCPListResourceTemplatesResult>;
readResource(uri: string): Promise<MCPReadResourceResult>;
invalidateToolsCache(): Promise<void>;
}
export declare class MCPServerSSE extends BaseMCPServerSSE implements MCPServerWithResources {
private underlying;
private readonly toolsLifecycle;
constructor(options: MCPServerSSEOptions);
get name(): string;
private invalidateToolsCaches;
connect(): Promise<void>;
close(): Promise<void>;
listTools(): Promise<MCPTool[]>;
callTool(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResultContent>;
callToolResult(toolName: string, args: Record<string, unknown> | null, meta?: Record<string, unknown> | null, options?: MCPCallToolOptions): Promise<CallToolResult>;
listResources(params?: MCPListResourcesParams): Promise<MCPListResourcesResult>;
listResourceTemplates(params?: MCPListResourcesParams): Promise<MCPListResourceTemplatesResult>;
readResource(uri: string): Promise<MCPReadResourceResult>;
invalidateToolsCache(): Promise<void>;
}
/**
* Fetches and flattens all tools from multiple MCP servers.
* Logs and skips any servers that fail to respond.
*/
/**
* Function signature for generating the MCP tool cache key.
* Customizable so the cache key can depend on any context—server, agent, runContext, etc.
*/
export type MCPToolCacheKeyGenerator = (params: {
server: MCPServer;
agent?: Agent<any, any>;
runContext?: RunContext<any>;
}) => string;
/**
* Default cache key generator for MCP tools.
* Uses server name, or server+agent if using callable filter.
*/
export declare const defaultMCPToolCacheKey: MCPToolCacheKeyGenerator;
/**
* Options for fetching MCP tools.
*/
export type GetAllMcpToolsOptions<TContext> = {
mcpServers: MCPServer[];
convertSchemasToStrict?: boolean;
runContext?: RunContext<TContext>;
agent?: Agent<TContext, any>;
generateMCPToolCacheKey?: MCPToolCacheKeyGenerator;
errorFunction?: MCPToolErrorFunction | null;
includeServerInToolNames?: boolean;
reservedToolNames?: Set<string>;
tracingParent?: Span<any>;
};
/**
* Returns all MCP tools from the provided servers, using the function tool conversion.
* If runContext and agent are provided, callable tool filters will be applied.
*/
export declare function getAllMcpTools<TContext = UnknownContext>(mcpServersOrOpts: MCPServer[] | GetAllMcpToolsOptions<TContext>, runContext?: RunContext<TContext>, agent?: Agent<TContext, any>, convertSchemasToStrict?: boolean): Promise<Tool<TContext>[]>;
/**
* Converts an MCP tool definition to a function tool for the Agents SDK.
*/
export type MCPFunctionToolConversionOptions = {
toolNameOverride?: string;
errorFunction?: MCPToolErrorFunction | null;
};
export declare function mcpToFunctionTool(mcpTool: MCPTool, server: MCPServer, convertSchemasToStrict: boolean, options?: MCPFunctionToolConversionOptions): FunctionTool<unknown, JsonObjectSchemaStrict<any>, string> | FunctionTool<unknown, JsonObjectSchemaNonStrict<any>, string>;
/**
* Abstract base class for MCP servers that use a ClientSession for communication.
* Handles session management, tool listing, tool calling, and cleanup.
*/
export interface BaseMCPServerStdioOptions {
env?: Record<string, string>;
cwd?: string;
cacheToolsList?: boolean;
/**
* Maximum successful pages per automatic `listTools()` call. Must be a positive
* integer; defaults to 64. Set a higher limit for larger listings.
* A terminal page at the limit succeeds; a fresh continuation at the limit
* rejects without returning or
* caching partial tools. Existing cursor-cycle handling is unchanged: modern
* clients end listing on a repeated cursor; legacy clients reject it.
* Request retries do not reset this budget. Does not limit page size or explicit
* resource pagination. Configure this option when constructing the server.
*/
maxListPages?: number;
clientSessionTimeoutSeconds?: number;
name?: string;
encoding?: string;
encodingErrorHandler?: 'strict' | 'ignore' | 'replace';
logger?: Logger;
toolFilter?: MCPToolFilterCallable | MCPToolFilterStatic;
/**
* Optional resolver for MCP request metadata (`_meta`) on tool calls.
* Invoked before calling `callTool`.
*/
toolMetaResolver?: MCPToolMetaResolver;
/**
* Whether to use MCP `structuredContent` as model-visible output when available.
*/
useStructuredContent?: boolean;
/**
* Optional callback that attaches SDK-only custom data to local MCP tool output items.
*/
customDataExtractor?: MCPToolCustomDataExtractor;
/** Guardrails applied before every tool on this server is invoked. */
toolInputGuardrails?: ToolInputGuardrailDefinition<any>[];
/** Guardrails applied after every tool on this server returns. */
toolOutputGuardrails?: ToolOutputGuardrailDefinition<any>[];
/**
* Optional function to convert MCP tool failures into model-visible messages.
* Set to null to rethrow errors instead of converting them.
*/
errorFunction?: MCPToolErrorFunction | null;
timeout?: number;
}
export interface DefaultMCPServerStdioOptions extends BaseMCPServerStdioOptions {
command: string;
args?: string[];
}
export interface FullCommandMCPServerStdioOptions extends BaseMCPServerStdioOptions {
fullCommand: string;
}
export type MCPServerStdioOptions = DefaultMCPServerStdioOptions | FullCommandMCPServerStdioOptions;
export interface MCPServerStreamableHttpOptions {
url: string;
cacheToolsList?: boolean;
/**
* Maximum successful pages per automatic `listTools()` call. Must be a positive
* integer; defaults to 64. Set a higher limit for larger listings.
* A terminal page at the limit succeeds; a fresh continuation at the limit
* rejects without returning or
* caching partial tools. Existing cursor-cycle handling is unchanged: modern
* clients end listing on a repeated cursor; legacy clients reject it.
* Request retries do not reset this budget. Does not limit page size or explicit
* resource pagination. Configure this option when constructing the server.
*/
maxListPages?: number;
clientSessionTimeoutSeconds?: number;
name?: string;
logger?: Logger;
toolFilter?: MCPToolFilterCallable | MCPToolFilterStatic;
/**
* Optional resolver for MCP request metadata (`_meta`) on tool calls.
* Invoked before calling `callTool`.
*/
toolMetaResolver?: MCPToolMetaResolver;
/**
* Whether to use MCP `structuredContent` as model-visible output when available.
*/
useStructuredContent?: boolean;
/**
* Optional callback that attaches SDK-only custom data to local MCP tool output items.
*/
customDataExtractor?: MCPToolCustomDataExtractor;
/** Guardrails applied before every tool on this server is invoked. */
toolInputGuardrails?: ToolInputGuardrailDefinition<any>[];
/** Guardrails applied after every tool on this server returns. */
toolOutputGuardrails?: ToolOutputGuardrailDefinition<any>[];
/**
* Optional function to convert MCP tool failures into model-visible messages.
* Set to null to rethrow errors instead of converting them.
*/
errorFunction?: MCPToolErrorFunction | null;
timeout?: number;
authProvider?: any;
requestInit?: any;
fetch?: any;
reconnectionOptions?: any;
sessionId?: string;
}
export interface MCPServerSSEOptions {
url: string;
cacheToolsList?: boolean;
/**
* Maximum successful pages per automatic `listTools()` call. Must be a positive
* integer; defaults to 64. Set a higher limit for larger listings.
* A terminal page at the limit succeeds; a fresh continuation at the limit
* rejects without returning or
* caching partial tools. Existing cursor-cycle handling is unchanged: modern
* clients end listing on a repeated cursor; legacy clients reject it.
* Request retries do not reset this budget. Does not limit page size or explicit
* resource pagination. Configure this option when constructing the server.
*/
maxListPages?: number;
clientSessionTimeoutSeconds?: number;
name?: string;
logger?: Logger;
toolFilter?: MCPToolFilterCallable | MCPToolFilterStatic;
/**
* Optional resolver for MCP request metadata (`_meta`) on tool calls.
* Invoked before calling `callTool`.
*/
toolMetaResolver?: MCPToolMetaResolver;
/**
* Whether to use MCP `structuredContent` as model-visible output when available.
*/
useStructuredContent?: boolean;
/**
* Optional callback that attaches SDK-only custom data to local MCP tool output items.
*/
customDataExtractor?: MCPToolCustomDataExtractor;
/** Guardrails applied before every tool on this server is invoked. */
toolInputGuardrails?: ToolInputGuardrailDefinition<any>[];
/** Guardrails applied after every tool on this server returns. */
toolOutputGuardrails?: ToolOutputGuardrailDefinition<any>[];
/**
* Optional function to convert MCP tool failures into model-visible messages.
* Set to null to rethrow errors instead of converting them.
*/
errorFunction?: MCPToolErrorFunction | null;
timeout?: number;
authProvider?: any;
requestInit?: any;
fetch?: any;
eventSourceInit?: any;
}
/**
* Represents a JSON-RPC request message.
*/
export interface JsonRpcRequest {
jsonrpc: '2.0';
id: number;
method: string;
params?: Record<string, unknown>;
}
/**
* Represents a JSON-RPC notification message (no response expected).
*/
export interface JsonRpcNotification {
jsonrpc: '2.0';
method: string;
params?: Record<string, unknown>;
}
/**
* Represents a JSON-RPC response message.
*/
export interface JsonRpcResponse {
jsonrpc: '2.0';
id: number;
result?: any;
error?: any;
}
export interface CallToolResponse extends JsonRpcResponse {
result: {
content: Array<{
type: string;
[key: string]: unknown;
}>;
_meta?: Record<string, unknown>;
structuredContent?: Record<string, unknown>;
isError?: boolean;
};
}
export type CallToolResult = CallToolResponse['result'];
export type CallToolResultMetadata = Pick<CallToolResult, '_meta' | 'structuredContent' | 'isError'>;
export type CallToolResultContent = CallToolResult['content'] & CallToolResultMetadata;
export interface InitializeResponse extends JsonRpcResponse {
result: {
protocolVersion: string;
capabilities: {
tools: Record<string, unknown>;
};
serverInfo: {
name: string;
version: string;
};
};
}
export type InitializeResult = InitializeResponse['result'];