> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mcp-use.com/llms.txt
> Use this file to discover all available pages before exploring further.

# MCPAgent

> API reference for MCPAgent constructor modes, run options, streaming methods, memory, and observability.

**Source Code**

View the source code for this module on GitHub:&#x20;

[[https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/src/agents/mcp\_agent.ts](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/src/agents/mcp_agent.ts)](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/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`](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/src/agents/types.ts), [`remote.ts`](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/src/agents/remote.ts), and [`agents/index.ts`](https://github.com/mcp-use/mcp-use/blob/main/libraries/typescript/packages/agent/src/agents/index.ts).

```ts wrap theme={null}
import { MCPAgent } from "@mcp-use/agent";
```

Import agent-specific exports from `@mcp-use/agent`:

```ts wrap theme={null}
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`](#explicitmodeoptions) or
> [`SimplifiedModeOptions`](#simplifiedmodeoptions).

**Returns**

> **returns** `MCPAgent`

**Signature**

```ts wrap theme={null}
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.

```ts wrap theme={null}
import { MCPAgent } from "@mcp-use/agent";

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.

```ts wrap theme={null}
import { ChatOpenAI } from "@langchain/openai";
import { MCPAgent } from "@mcp-use/agent";
import { MCPClient } from "@mcp-use/client";

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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
initialize(): Promise<void>
```

> [!NOTE]
>
> `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: 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.

**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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
run(options: RunOptions): Promise<string>
run<T>(options: RunOptions<T>): Promise<T>
```

> [!WARNING]
>
> 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`](#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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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`](#run).

**Returns**

> **returns** `AsyncGenerator\<StreamEvent, void, void\>`

**Example**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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`](#run).

**Returns**

> **returns** `AsyncGenerator\<void, string, void\>`

**Example**

```ts wrap theme={null}
for await (const _ of agent.prettyStreamEvents({
  prompt: "List all available MCP tools.",
})) {
  // Output is printed by the formatter.
}
```

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
clearConversationHistory(): void
```

### getSystemMessage

Returns the active LangChain `SystemMessage`, or `null` before initialization when no system message has been created.

**Returns**

> **returns** `SystemMessage | null`

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
setDisallowedTools(disallowedTools: string[]): void
```

### getDisallowedTools

Returns the current disallowed tool name list.

**Returns**

> **returns** `string[]`

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
setMetadata(newMetadata: Record<string, any>): void
```

### getMetadata

Returns a copy of the current observability metadata.

**Returns**

> **returns** `Record\<string, any\>`

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
setTags(newTags: string[]): void
```

### getTags

Returns a copy of the current observability tags.

**Returns**

> **returns** `string[]`

**Signature**

```ts wrap theme={null}
getTags(): string[]
```

### flush

Flushes observability traces through the configured `ObservabilityManager`. Use this in serverless functions before the function exits.

**Returns**

> **returns** `Promise\<void\>`

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
close(): Promise<void>
```

## Properties

### toolsUsedNames

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

**Type**

```ts theme={null}
string[]
```

### observabilityManager

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

**Type**

```ts theme={null}
ObservabilityManager;
```

## Types

### MCPAgentOptions

Union of explicit and simplified constructor options.

**Signature**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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**

```ts wrap theme={null}
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 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.

**Signature**

```ts wrap theme={null}
interface MCPServerConfig {
  command?: string;
  args?: string[];
  env?: Record<string, string>;
  url?: string;
  headers?: Record<string, string>;
  auth_token?: string;
  authToken?: string;
}
```

### 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**

```ts wrap theme={null}
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[]`
>
> Additional history appended after the native agent's stored memory and
> before provider messages and the current prompt.
>
> **schema** `ZodSchema\<T\>`
>
> Zod schema for structured output.
>
> **signal** `AbortSignal`
>
> Abort signal for cancellation.

**Signature**

```ts wrap theme={null}
interface RunOptions<T = string> {
  prompt: string;
  maxSteps?: number;
  manageConnector?: boolean;
  externalHistory?: BaseMessage[];
  schema?: ZodSchema<T>;
  signal?: AbortSignal;
}
```

> [!NOTE]
>
> `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](https://docs.mcp-use.com/v1/typescript/agent/index.md): task-focused guide for building MCP agents.
* [Streaming](https://docs.mcp-use.com/v1/typescript/agent/streaming.md): guide for step streaming and low-level event streaming.
* [Structured output](https://docs.mcp-use.com/v1/typescript/agent/structured-output.md): guide for Zod schema results.
* [Observability](https://docs.mcp-use.com/v1/typescript/agent/observability.md): guide for tracing, metadata, and callbacks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.