Skip to main content
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.
import { MCPAgent } from "mcp-use";
Use the mcp-use/agent subpath when you want agent-specific exported types:
import { MCPAgent } from "mcp-use/agent";
import type { MCPAgentOptions, MCPServerConfig, LLMConfig } from "mcp-use/agent";

Constructor

Creates an MCP agent. The constructor supports explicit mode, where you provide a model and MCPClient or connectors, and simplified mode, where you provide a "provider/model" string and mcpServers configuration. Parameters
options
MCPAgentOptions
required
Agent configuration. Use either ExplicitModeOptions or SimplifiedModeOptions.
Returns
returns
MCPAgent
Signature
constructor(options: MCPAgentOptions)

Simplified mode

In simplified mode, MCPAgent creates the MCPClient and LLM during initialize(). The llm value must use the "provider/model" format.
import { MCPAgent } from "mcp-use";

const agent = new MCPAgent({
  llm: "openai/gpt-4o",
  mcpServers: {
    filesystem: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
    },
  },
});

const result = await agent.run({
  prompt: "Summarize the files in this directory.",
});

console.log(result);
await agent.close();

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.
import { ChatOpenAI } from "@langchain/openai";
import { MCPAgent, MCPClient } from "mcp-use";

const client = new MCPClient({
  mcpServers: {
    filesystem: {
      command: "npx",
      args: ["-y", "@modelcontextprotocol/server-filesystem", "./"],
    },
  },
});

const agent = new MCPAgent({
  llm: new ChatOpenAI({ model: "gpt-4o" }),
  client,
  maxSteps: 10,
});

await agent.initialize();
const result = await agent.run({ prompt: "List the available tools." });

console.log(result);
await agent.close();

Methods

getPackageVersion

Returns the installed mcp-use package version. Returns
returns
string
Signature
static getPackageVersion(): string

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 the MCPClient and LLM from the constructor options. Returns
returns
Promise<void>
Signature
initialize(): Promise<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. Parameters
options.prompt
string
required
User request to send to the agent.
options.maxSteps
number
default:"constructor maxSteps"
Maximum model-call steps for this run. The constructor default is 5.
options.manageConnector
boolean
default:"true"
Whether the agent should initialize connections before the run and clean up connector-only runs after completion.
options.externalHistory
BaseMessage[]
default:"conversation history"
History to use for this run instead of the agent’s stored conversation history.
options.schema
ZodSchema<T>
default:"undefined"
Schema for structured output. When present, run() returns Promise<T>.
options.signal
AbortSignal
default:"undefined"
Abort signal passed to the underlying LangChain execution.
Returns
returns
Promise<string | T>
Example
import { z } from "zod";

const summary = await agent.run({
  prompt: "Inspect the project and summarize the package scripts.",
  maxSteps: 8,
});

const analysis = await agent.run({
  prompt: "Count the TypeScript files by directory.",
  schema: z.object({
    totalFiles: z.number(),
    directories: z.array(
      z.object({
        path: z.string(),
        count: z.number(),
      })
    ),
  }),
});
Signature
run(options: RunOptions): Promise<string>
run<T>(options: RunOptions<T>): Promise<T>
The positional overloads (run(query, maxSteps, manageConnector, externalHistory, outputSchema, signal)) are still supported for compatibility, but they are deprecated. Prefer the options object form.

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. Parameters
options
RunOptions<T>
required
Same options object accepted by run.
Yields
AgentStep.action.tool
string
Name of the tool the agent called.
AgentStep.action.toolInput
any
Arguments passed to the tool.
AgentStep.action.log
string
Short text description of the tool call.
AgentStep.observation
string
Tool observation text when available.
Returns
returns
AsyncGenerator<AgentStep, string | T, void>
Example
for await (const step of agent.stream({
  prompt: "Find the README and summarize it.",
  maxSteps: 6,
})) {
  console.log(step.action.tool, step.action.toolInput);
}
Signature
stream(options: RunOptions): AsyncGenerator<AgentStep, string, void>
stream<T>(options: RunOptions<T>): AsyncGenerator<AgentStep, T, void>

streamEvents

Streams low-level LangChain StreamEvent objects from the underlying agent executor. Use this method for token streaming, detailed progress UIs, and custom event handling. Parameters
options
RunOptions<T>
required
Same options object accepted by run.
Returns
returns
AsyncGenerator<StreamEvent, void, void>
Example
for await (const event of agent.streamEvents({
  prompt: "Search the MCP server for project metadata.",
})) {
  if (event.event === "on_chat_model_stream") {
    const content = event.data?.chunk?.content ?? event.data?.chunk?.text;
    if (content) process.stdout.write(String(content));
  }
}
Signature
streamEvents(options: RunOptions): AsyncGenerator<StreamEvent, void, void>
streamEvents<T>(options: RunOptions<T>): AsyncGenerator<StreamEvent, void, void>

prettyStreamEvents

Streams low-level events through the built-in terminal formatter. This method is intended for CLIs and local development output. Parameters
options
RunOptions<T>
required
Same options object accepted by run.
Returns
returns
AsyncGenerator<void, string, void>
Example
for await (const _ of agent.prettyStreamEvents({
  prompt: "List all available MCP tools.",
})) {
  // Output is printed by the formatter.
}
Signature
prettyStreamEvents(options: RunOptions): AsyncGenerator<void, string, void>
prettyStreamEvents<T>(options: RunOptions<T>): AsyncGenerator<void, string, void>

getConversationHistory

Returns a copy of the current conversation history. Conversation memory is enabled by default. Returns
returns
BaseMessage[]
Signature
getConversationHistory(): BaseMessage[]

clearConversationHistory

Clears stored conversation history. When memory is enabled and a system message exists, the system message is preserved. Returns
returns
void
Signature
clearConversationHistory(): void

getSystemMessage

Returns the active LangChain SystemMessage, or null before initialization when no system message has been created. Returns
returns
SystemMessage | null
Signature
getSystemMessage(): SystemMessage | 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. Parameters
message
string
required
System message content.
Returns
returns
void
Signature
setSystemMessage(message: string): void

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. Parameters
disallowedTools
string[]
required
Tool names to hide from the agent.
Returns
returns
void
Signature
setDisallowedTools(disallowedTools: string[]): void

getDisallowedTools

Returns the current disallowed tool name list. Returns
returns
string[]
Signature
getDisallowedTools(): string[]

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. Parameters
newMetadata
Record<string, any>
required
Serializable key-value pairs to attach to observability traces.
Returns
returns
void
Signature
setMetadata(newMetadata: Record<string, any>): void

getMetadata

Returns a copy of the current observability metadata. Returns
returns
Record<string, any>
Signature
getMetadata(): Record<string, any>

setTags

Adds tags to observability traces. Tags are sanitized, deduplicated, and limited to 50 characters. Parameters
newTags
string[]
required
Tags to attach to observability traces.
Returns
returns
void
Signature
setTags(newTags: string[]): void

getTags

Returns a copy of the current observability tags. Returns
returns
string[]
Signature
getTags(): string[]

flush

Flushes observability traces through the configured ObservabilityManager. Use this in serverless functions before the function exits. Returns
returns
Promise<void>
Signature
flush(): Promise<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. Returns
returns
Promise<void>
Signature
close(): Promise<void>

Properties

toolsUsedNames

Public array of tool names called during agent execution. The array is appended to as runs execute. Type
string[]

observabilityManager

Public ObservabilityManager instance used to create callbacks, flush traces, and shut down observability integrations. Type
ObservabilityManager

Types

MCPAgentOptions

Union of explicit and simplified constructor options. Signature
type MCPAgentOptions = ExplicitModeOptions | SimplifiedModeOptions;

ExplicitModeOptions

Options for constructing an agent from a pre-instantiated LLM plus an MCPClient or direct connectors. Fields
llm
LanguageModel
required
LangChain-compatible chat model instance.
client
MCPClient
MCP client. Required when connectors is omitted and required for useServerManager.
connectors
BaseConnector[]
Direct connectors. Required when client is omitted.
maxSteps
number
Default maximum agent steps. Defaults to 5.
autoInitialize
boolean
Initialize automatically when a run starts and connector management did not initialize the agent. Defaults to false.
memoryEnabled
boolean
Store conversation history across runs. Defaults to true.
systemPrompt
string | null
System prompt override. Defaults to null.
systemPromptTemplate
string | null
Template override used when generating the system message from tools. Defaults to null.
additionalInstructions
string | null
Extra instructions appended to the generated system prompt. Defaults to null.
disallowedTools
string[]
Tool names to hide from the agent. Defaults to [].
additionalTools
StructuredToolInterface[]
Extra LangChain tools to add after MCP tools are created. Defaults to [].
toolsUsedNames
string[]
Initial tool usage list. Defaults to [].
exposeResourcesAsTools
boolean
Expose MCP resources as tools. Defaults to true.
exposePromptsAsTools
boolean
Expose MCP prompts as tools. Defaults to true.
useServerManager
boolean
Use ServerManager tools instead of exposing all server tools directly. Defaults to false.
verbose
boolean
Enable verbose observability output. Defaults to false.
observe
boolean
Enable observability callback setup. Defaults to true.
adapter
LangChainAdapter
Custom adapter for converting MCP tools, resources, and prompts to LangChain tools.
serverManagerFactory
(client: MCPClient) => ServerManager
Factory for custom server manager instances.
callbacks
BaseCallbackHandler[]
Custom LangChain callback handlers.
Signature
interface ExplicitModeOptions {
  llm: LanguageModel;
  client?: MCPClient;
  connectors?: BaseConnector[];
  maxSteps?: number;
  autoInitialize?: boolean;
  memoryEnabled?: boolean;
  systemPrompt?: string | null;
  systemPromptTemplate?: string | null;
  additionalInstructions?: string | null;
  disallowedTools?: string[];
  additionalTools?: StructuredToolInterface[];
  toolsUsedNames?: string[];
  exposeResourcesAsTools?: boolean;
  exposePromptsAsTools?: boolean;
  useServerManager?: boolean;
  verbose?: boolean;
  observe?: boolean;
  adapter?: LangChainAdapter;
  serverManagerFactory?: (client: MCPClient) => ServerManager;
  callbacks?: BaseCallbackHandler[];
}

SimplifiedModeOptions

Options for constructing an agent from an LLM string and MCP server configuration. The agent creates the LLM and client internally during initialization. Fields
llm
string
required
LLM identifier in "provider/model" format, such as "openai/gpt-4o" or "anthropic/claude-sonnet-4-6".
mcpServers
Record<string, MCPServerConfig>
required
MCP server connection configuration keyed by server name.
llmConfig
LLMConfig
Provider-specific LLM configuration such as apiKey, temperature, maxTokens, and topP.
maxSteps
number
Default maximum agent steps. Defaults to 5.
autoInitialize
boolean
Initialize automatically when a run starts and connector management did not initialize the agent. Defaults to false.
memoryEnabled
boolean
Store conversation history across runs. Defaults to true.
systemPrompt
string | null
System prompt override. Defaults to null.
systemPromptTemplate
string | null
Template override used when generating the system message from tools. Defaults to null.
additionalInstructions
string | null
Extra instructions appended to the generated system prompt. Defaults to null.
disallowedTools
string[]
Tool names to hide from the agent. Defaults to [].
additionalTools
StructuredToolInterface[]
Extra LangChain tools to add after MCP tools are created. Defaults to [].
exposeResourcesAsTools
boolean
Expose MCP resources as tools. Defaults to true.
exposePromptsAsTools
boolean
Expose MCP prompts as tools. Defaults to true.
useServerManager
boolean
Use ServerManager tools instead of exposing all server tools directly. Defaults to false.
verbose
boolean
Enable verbose observability output. Defaults to false.
observe
boolean
Enable observability callback setup. Defaults to true.
callbacks
BaseCallbackHandler[]
Custom LangChain callback handlers.
Signature
interface SimplifiedModeOptions {
  llm: string;
  llmConfig?: LLMConfig;
  mcpServers: Record<string, MCPServerConfig>;
  maxSteps?: number;
  autoInitialize?: boolean;
  memoryEnabled?: boolean;
  systemPrompt?: string | null;
  systemPromptTemplate?: string | null;
  additionalInstructions?: string | null;
  disallowedTools?: string[];
  additionalTools?: StructuredToolInterface[];
  exposeResourcesAsTools?: boolean;
  exposePromptsAsTools?: boolean;
  useServerManager?: boolean;
  verbose?: boolean;
  observe?: boolean;
  callbacks?: BaseCallbackHandler[];
}

MCPServerConfig

Configuration for an MCP server in simplified mode. Fields
command
string
Command for a stdio server.
args
string[]
Arguments passed to command.
env
Record<string, string>
Environment variables for the server process.
url
string
URL for a remote HTTP or SSE MCP server.
headers
Record<string, string>
Headers sent to remote MCP servers.
auth_token
string
Bearer token value accepted by existing config shapes.
authToken
string
Bearer token value accepted by existing config shapes.
transport
"http" | "sse"
Remote transport preference.
preferSse
boolean
Prefer SSE when both transports are possible.
Signature
interface MCPServerConfig {
  command?: string;
  args?: string[];
  env?: Record<string, string>;
  url?: string;
  headers?: Record<string, string>;
  auth_token?: string;
  authToken?: string;
  transport?: "http" | "sse";
  preferSse?: boolean;
}

LLMConfig

Configuration passed to internally created LangChain model instances in simplified mode. Fields
apiKey
string
Provider API key. If omitted, the provider-specific environment variable is used.
temperature
number
Sampling temperature.
maxTokens
number
Maximum output tokens.
topP
number
Nucleus sampling value.
[key: string]
any
Additional provider-specific LangChain model options.
Signature
interface LLMConfig {
  apiKey?: string;
  temperature?: number;
  maxTokens?: number;
  topP?: number;
  [key: string]: any;
}

RunOptions

Options object accepted by run, stream, streamEvents, and prettyStreamEvents. Fields
prompt
string
required
User request to send to the agent.
maxSteps
number
Per-call step limit override.
manageConnector
boolean
Whether the agent manages initialization and connector cleanup for the call.
externalHistory
BaseMessage[]
Conversation history override for the call.
schema
ZodSchema<T>
Zod schema for structured output.
signal
AbortSignal
Abort signal for cancellation.
Signature
interface RunOptions<T = string> {
  prompt: string;
  maxSteps?: number;
  manageConnector?: boolean;
  externalHistory?: BaseMessage[];
  schema?: ZodSchema<T>;
  signal?: AbortSignal;
}
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.