View the source code for this module on GitHub: https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/mcp-use/src/agents/mcp_agent.ts
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 subpath when you want agent-specific exported types:
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
ReturnsAgent configuration. Use eitherExplicitModeOptionsorSimplifiedModeOptions.
Signature
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
Signature
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
Signature
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. ParametersReturnsUser request to send to the agent.Maximum model-call steps for this run. The constructor default is5.Whether the agent should initialize connections before the run and clean up connector-only runs after completion.History to use for this run instead of the agent’s stored conversation history.Schema for structured output. When present,run()returnsPromise<T>.Abort signal passed to the underlying LangChain execution.
Example
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
ReturnsName of the tool the agent called.Arguments passed to the tool.Short text description of the tool call.Tool observation text when available.
Example
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
Example
prettyStreamEvents
Streams low-level events through the built-in terminal formatter. This method is intended for CLIs and local development output. ParametersReturns
Example
getConversationHistory
Returns a copy of the current conversation history. Conversation memory is enabled by default. ReturnsSignature
clearConversationHistory
Clears stored conversation history. When memory is enabled and a system message exists, the system message is preserved. ReturnsSignature
getSystemMessage
Returns the active LangChainSystemMessage, or null before initialization when no system message has been created.
Returns
Signature
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. ParametersReturnsSystem message content.
Signature
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. ParametersReturnsTool names to hide from the agent.
Signature
getDisallowedTools
Returns the current disallowed tool name list. ReturnsSignature
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. ParametersReturnsSerializable key-value pairs to attach to observability traces.
Signature
getMetadata
Returns a copy of the current observability metadata. ReturnsSignature
setTags
Adds tags to observability traces. Tags are sanitized, deduplicated, and limited to 50 characters. ParametersReturnsTags to attach to observability traces.
Signature
getTags
Returns a copy of the current observability tags. ReturnsSignature
flush
Flushes observability traces through the configuredObservabilityManager. Use this in serverless functions before the function exits.
Returns
Signature
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. ReturnsSignature
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
SignatureLangChain-compatible chat model instance.MCP client. Required whenconnectorsis omitted and required foruseServerManager.Direct connectors. Required whenclientis omitted.Default maximum agent steps. Defaults to5.Initialize automatically when a run starts and connector management did not initialize the agent. Defaults tofalse.Store conversation history across runs. Defaults totrue.System prompt override. Defaults tonull.Template override used when generating the system message from tools. Defaults tonull.Extra instructions appended to the generated system prompt. Defaults tonull.Tool names to hide from the agent. Defaults to[].Extra LangChain tools to add after MCP tools are created. Defaults to[].Initial tool usage list. Defaults to[].Expose MCP resources as tools. Defaults totrue.Expose MCP prompts as tools. Defaults totrue.UseServerManagertools instead of exposing all server tools directly. Defaults tofalse.Enable verbose observability output. Defaults tofalse.Enable observability callback setup. Defaults totrue.Custom adapter for converting MCP tools, resources, and prompts to LangChain tools.Factory for custom server manager instances.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. FieldsSignatureLLM identifier in"provider/model"format, such as"openai/gpt-4o"or"anthropic/claude-sonnet-4-6".MCP server connection configuration keyed by server name.Provider-specific LLM configuration such asapiKey,temperature,maxTokens, andtopP.Default maximum agent steps. Defaults to5.Initialize automatically when a run starts and connector management did not initialize the agent. Defaults tofalse.Store conversation history across runs. Defaults totrue.System prompt override. Defaults tonull.Template override used when generating the system message from tools. Defaults tonull.Extra instructions appended to the generated system prompt. Defaults tonull.Tool names to hide from the agent. Defaults to[].Extra LangChain tools to add after MCP tools are created. Defaults to[].Expose MCP resources as tools. Defaults totrue.Expose MCP prompts as tools. Defaults totrue.UseServerManagertools instead of exposing all server tools directly. Defaults tofalse.Enable verbose observability output. Defaults tofalse.Enable observability callback setup. Defaults totrue.Custom LangChain callback handlers.
MCPServerConfig
Configuration for an MCP server in simplified mode. FieldsSignatureCommand for a stdio server.Arguments passed tocommand.Environment variables for the server process.URL for a remote HTTP or SSE MCP server.Headers sent to remote MCP servers.Bearer token value accepted by existing config shapes.Bearer token value accepted by existing config shapes.Remote transport preference.Prefer SSE when both transports are possible.
LLMConfig
Configuration passed to internally created LangChain model instances in simplified mode. FieldsSignatureProvider API key. If omitted, the provider-specific environment variable is used.Sampling temperature.Maximum output tokens.Nucleus sampling value.Additional provider-specific LangChain model options.
RunOptions
Options object accepted byrun, stream, streamEvents, and prettyStreamEvents.
Fields
SignatureUser request to send to the agent.Per-call step limit override.Whether the agent manages initialization and connector cleanup for the call.Conversation history override for the call.Zod schema for structured output.Abort 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.