MCPAgent connects a LangChain-compatible chat model to MCP servers. It discovers MCP tools, resources, and prompts, exposes them as LangChain tools, runs a multi-step agent loop, and returns either a string or a Zod-validated structured result.
Related source files: types.ts, remote.ts, and agents/index.ts.
@mcp-use/agent:
Constructor
Creates an MCP agent. The constructor supports explicit mode, where you provide a model andMCPClient or connectors, and simplified mode, where you provide a "provider/model" string and mcpServers configuration.
Parameters
ReturnsMCPAgentOptionsrequiredAgent configuration. Use eitherExplicitModeOptionsorSimplifiedModeOptions.
SignatureMCPAgent
Simplified mode
In simplified mode,MCPAgent creates the MCPClient and LLM during initialize(). The llm value must use the "provider/model" format.
Explicit mode
In explicit mode, you create the model and client yourself. Use this mode when you need full control over the LLM instance, client lifecycle, connectors, callbacks, or server manager.Methods
getPackageVersion
Returns the installedmcp-use package version.
Returns
Signaturestring
initialize
Connects to MCP servers, creates LangChain tools, builds the system message, configures observability callbacks, and creates the underlying LangChain agent executor. In simplified mode, this also creates theMCPClient and LLM from the constructor options.
Returns
SignaturePromise<void>
run() initializes the agent when connector management is enabled. Call
initialize() yourself when you want explicit lifecycle control before
stream(), streamEvents(), or repeated runs.run
Runs a prompt to completion and returns the final result. Without a schema, the result is a string. With a Zod schema, the result is parsed and returned as the schema’s inferred type. ParametersstringrequiredUser request to send to the agent.
number
default:"constructor maxSteps"
Maximum model-call steps for this run. The constructor default is
5.boolean
default:"true"
Whether the agent should initialize connections before the run and clean up connector-only runs after completion.
BaseMessage[]
default:"undefined"
Additional LangChain-formatted history for this run. The native agent places stored memory first (when enabled), then
externalHistory, messages, and the current prompt. Supplying it does not clear or replace stored memory.ZodSchema<T>
default:"undefined"
Schema for structured output. When present,
run() returns Promise<T>.AbortSignal
default:"undefined"
Abort signal passed to the underlying LangChain execution.
ExamplePromise<string | T>
stream
Streams high-level agent steps and returns the final answer as the async generator’s return value. Each yielded step represents a tool call. Tool observations are logged internally and may be empty in the yielded object. ParametersYields
ReturnsstringName of the tool the agent called.anyArguments passed to the tool.stringShort text description of the tool call.stringTool observation text when available.
ExampleAsyncGenerator<AgentStep, string | T, void>
streamEvents
Streams low-level LangChainStreamEvent objects from the underlying agent executor. Use this method for token streaming, detailed progress UIs, and custom event handling.
Parameters
Returns
ExampleAsyncGenerator<StreamEvent, void, void>
prettyStreamEvents
Streams low-level events through the built-in terminal formatter. This method is intended for CLIs and local development output. ParametersReturns
ExampleAsyncGenerator<void, string, void>
getConversationHistory
Returns a copy of the current conversation history. Conversation memory is enabled by default. ReturnsSignatureBaseMessage[]
clearConversationHistory
Clears stored conversation history. When memory is enabled and a system message exists, the system message is preserved. ReturnsSignaturevoid
getSystemMessage
Returns the active LangChainSystemMessage, or null before initialization when no system message has been created.
Returns
SignatureSystemMessage | null
setSystemMessage
Replaces the active system message. If the agent is already initialized and tools are loaded, the underlying agent executor is recreated with the new message. ParametersReturnsstringrequiredSystem message content.
Signaturevoid
setDisallowedTools
Sets the list of tool names that should not be exposed to the agent. If the agent is already initialized, reinitialize the agent for the change to affect generated tools. ParametersReturnsstring[]requiredTool names to hide from the agent.
Signaturevoid
getDisallowedTools
Returns the current disallowed tool name list. ReturnsSignaturestring[]
setMetadata
Merges metadata into the current observability metadata. Keys are sanitized by replacing unsupported characters with underscores. Object values are serialized for validation and large serialized values are truncated. ParametersReturnsRecord<string, any>requiredSerializable key-value pairs to attach to observability traces.
Signaturevoid
getMetadata
Returns a copy of the current observability metadata. ReturnsSignatureRecord<string, any>
setTags
Adds tags to observability traces. Tags are sanitized, deduplicated, and limited to 50 characters. ParametersReturnsstring[]requiredTags to attach to observability traces.
Signaturevoid
getTags
Returns a copy of the current observability tags. ReturnsSignaturestring[]
flush
Flushes observability traces through the configuredObservabilityManager. Use this in serverless functions before the function exits.
Returns
SignaturePromise<void>
close
Closes agent resources, shuts down observability handlers, clears tools and the executor, closes the client or disconnects direct connectors, and marks the agent as uninitialized. ReturnsSignaturePromise<void>
Properties
toolsUsedNames
Public array of tool names called during agent execution. The array is appended to as runs execute. TypeobservabilityManager
PublicObservabilityManager instance used to create callbacks, flush traces, and shut down observability integrations.
Type
Types
MCPAgentOptions
Union of explicit and simplified constructor options. SignatureExplicitModeOptions
Options for constructing an agent from a pre-instantiated LLM plus anMCPClient or direct connectors.
Fields
SignatureLanguageModelrequiredLangChain-compatible chat model instance.MCPClientMCP client. Required whenconnectorsis omitted and required foruseServerManager.BaseConnector[]Direct connectors. Required whenclientis omitted.numberDefault maximum agent steps. Defaults to5.booleanInitialize automatically when a run starts and connector management did not initialize the agent. Defaults tofalse.booleanStore conversation history across runs. Defaults totrue.string | nullSystem prompt override. Defaults tonull.string | nullTemplate override used when generating the system message from tools. Defaults tonull.string | nullExtra instructions appended to the generated system prompt. Defaults tonull.string[]Tool names to hide from the agent. Defaults to[].StructuredToolInterface[]Extra LangChain tools to add after MCP tools are created. Defaults to[].string[]Initial tool usage list. Defaults to[].booleanExpose MCP resources as tools. Defaults totrue.booleanExpose MCP prompts as tools. Defaults totrue.booleanUseServerManagertools instead of exposing all server tools directly. Defaults tofalse.booleanEnable verbose observability output. Defaults tofalse.booleanEnable observability callback setup. Defaults totrue.LangChainAdapterCustom adapter for converting MCP tools, resources, and prompts to LangChain tools.(client: MCPClient) => ServerManagerFactory for custom server manager instances.BaseCallbackHandler[]Custom LangChain callback handlers.
SimplifiedModeOptions
Options for constructing an agent from an LLM string and MCP server configuration. The agent creates the LLM and client internally during initialization. FieldsSignaturestringrequiredLLM identifier in"provider/model"format, such as"openai/gpt-4o"or"anthropic/claude-sonnet-4-6".Record<string, MCPServerConfig>requiredMCP server connection configuration keyed by server name.LLMConfigProvider-specific LLM configuration such asapiKey,temperature,maxTokens, andtopP.numberDefault maximum agent steps. Defaults to5.booleanInitialize automatically when a run starts and connector management did not initialize the agent. Defaults tofalse.booleanStore conversation history across runs. Defaults totrue.string | nullSystem prompt override. Defaults tonull.string | nullTemplate override used when generating the system message from tools. Defaults tonull.string | nullExtra instructions appended to the generated system prompt. Defaults tonull.string[]Tool names to hide from the agent. Defaults to[].StructuredToolInterface[]Extra LangChain tools to add after MCP tools are created. Defaults to[].booleanExpose MCP resources as tools. Defaults totrue.booleanExpose MCP prompts as tools. Defaults totrue.booleanUseServerManagertools instead of exposing all server tools directly. Defaults tofalse.booleanEnable verbose observability output. Defaults tofalse.booleanEnable observability callback setup. Defaults totrue.BaseCallbackHandler[]Custom LangChain callback handlers.
MCPServerConfig
Configuration for an MCP server in simplified mode. FieldsSignaturestringCommand for a stdio server.string[]Arguments passed tocommand.Record<string, string>Environment variables for the server process.stringURL for a remote HTTP MCP server.Record<string, string>Headers sent to remote MCP servers.stringBearer token value accepted by existing config shapes.stringBearer token value accepted by existing config shapes.
LLMConfig
Configuration passed to internally created LangChain model instances in simplified mode. FieldsSignaturestringProvider API key. If omitted, the provider-specific environment variable is used.numberSampling temperature.numberMaximum output tokens.numberNucleus sampling value.anyAdditional provider-specific LangChain model options.
RunOptions
Options object accepted byrun, stream, streamEvents, and prettyStreamEvents.
Fields
SignaturestringrequiredUser request to send to the agent.numberPer-call step limit override.booleanWhether the agent manages initialization and connector cleanup for the call.BaseMessage[]Additional history appended after the native agent’s stored memory and before provider messages and the current prompt.ZodSchema<T>Zod schema for structured output.AbortSignalAbort signal for cancellation.
RunOptions is defined in the mcp_agent.ts source file. It is used
structurally by the public methods, so you can pass an object with these
fields without importing the interface.Related
- Agent guide: task-focused guide for building MCP agents.
- Streaming: guide for step streaming and low-level event streaming.
- Structured output: guide for Zod schema results.
- Observability: guide for tracing, metadata, and callbacks.