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

# Configure MCP Servers

> Declare MCP servers on an agent and inject credentials via Vaults so hosted agents can call third-party MCP tools.

Model Context Protocol (MCP) is a standard protocol for connecting external capabilities. Kimi Hosted Agents natively supports remote MCP servers: declare the server endpoint on your agent, and at session runtime the platform automatically connects, fetches the tool list, and exposes those tools to the model—tool discovery, invocation, and result delivery are all handled by the platform, so you do not need to write any MCP client code.

Integration is split cleanly into two steps:

* **Declare connections on the agent**: `mcp_servers` stores only server connection details and non-sensitive request headers, with zero credentials.
* **Inject credentials when creating a session**: Access credentials are stored in [Vaults](https://platform.kimi.ai/docs/hosted-agents/vaults.md). Bind a vault by ID when creating a session, and the platform automatically matches and injects credentials by server URL.

> [!NOTE]
>
> This separation lets a single agent definition serve multiple end users: each user has their own vault and credentials while the agent configuration stays generic.

The examples below read your API key from the `KIMI_API_KEY` environment variable.

## Declare MCP servers

Declare MCP servers via the `mcp_servers` field when creating or updating an agent:

| Field | Type | Description |
| - | - | - |
| `type` | string | Server type; currently only `"url"` is supported (remote server over streamable HTTP) |
| `name` | string | Server name, which must be unique within the same agent; referenced via `mcp_server_name` in `mcp_toolset` when configuring individual tools |
| `url` | string | Endpoint URL of the MCP server, which also serves as the matching key for credentials in a vault |
| `headers` | object | Optional non-sensitive HTTP request headers, up to 16 entries; accepted in requests and omitted from responses |

When updating an agent, the entire `mcp_servers` array is replaced, and any server omitted from the request is removed. `headers` follows a different rule: if `headers` is omitted or empty and the server's `name`, `type`, and `url` are unchanged, existing headers are preserved; if `headers` is non-empty, it replaces all headers for that server, and setting a key to an empty string deletes that key. Each agent can declare at most 20 MCP servers. **Declared servers are exposed automatically**: once connected, all tools provided by that MCP server become available to the model by default without declaring an `mcp_toolset`. You only need an `mcp_toolset` entry in `tools`—referencing the server via `mcp_server_name`—when you want to customize `default_config` or per-tool `configs`.

```bash cURL theme={null}
curl -X POST https://api.moonshot.ai/v1/agents \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Project Assistant",
    "model": {"id": "kimi-k3.1-pro"},
    "system": "You are a project management assistant that helps users track task progress.",
    "mcp_servers": [
      {
        "type": "url",
        "name": "todo",
        "url": "https://mcp.example.com/mcp"
      }
    ]
  }'
```

```bash CLI theme={null}
kha agents create --file - <<'JSON'
{
  "name": "Project Assistant",
  "model": {"id": "kimi-k3.1-pro"},
  "system": "You are a project management assistant that helps users track task progress.",
  "mcp_servers": [
    {
      "type": "url",
      "name": "todo",
      "url": "https://mcp.example.com/mcp"
    }
  ]
}
JSON
```

> [!NOTE]
>
> Because `url` is the matching key for vault credentials, provide a canonical server endpoint URL without query parameters, fragments, or userinfo—URLs containing those components cannot match vault credentials and are rejected when creating or updating the agent.

### Configure per-tool enablement and permissions

For fine-grained control, add an `mcp_toolset` entry in `tools` referencing a declared server to override settings per tool; omit `mcp_toolset` if you want all tools exposed with default settings:

```json theme={null}
{
  "tools": [
    {
      "type": "mcp_toolset",
      "mcp_server_name": "todo",
      "default_config": {"enabled": true},
      "configs": [
        {"name": "delete_task", "enabled": false}
      ]
    }
  ]
}
```

| Option | Description |
| - | - |
| `mcp_server_name` | Required; references a server `name` declared in the same agent's `mcp_servers` |
| `default_config.enabled` | Whether all tools from this server are enabled by default; enabled when omitted |
| `configs[].name` | Original tool name exposed by the MCP server |
| `configs[].enabled` | Per-tool enablement override; disabled tools are excluded from the model context |
| `configs[].permission_policy` | Per-tool permission policy; see [Permissions](https://platform.kimi.ai/docs/hosted-agents/permissions.md) |

If `configs` references a tool name that the server no longer exposes, no error is raised and that entry is silently ignored—server tool catalogs can evolve across versions without breaking your agent configuration.

> [!TIP]
>
> Permission policies support `always_allow` and `always_ask`. `always_ask` pauses execution after emitting `agent.tool_use` and waits for the client to reply with `user.tool_confirmation`; to prevent an agent from using a tool altogether, disable it with `enabled: false`. See [Permissions](https://platform.kimi.ai/docs/hosted-agents/permissions.md).

## Inject credentials via Vaults

Never place credentials in `mcp_servers`. Store access credentials in a vault and bind the vault in `resources` when creating a session. Different credential types are matched according to their own rules:

* **`environment_variable` credentials**: Used for placeholder substitution in permitted outbound requests, not as connection credentials for MCP servers. Raw secret values are never written to the filesystem or environment variables.
* **MCP credentials**: `mcp_oauth` and `static_bearer` credentials match by MCP server endpoint (`url`). When a match is found, the connection includes the corresponding authentication header; when no matching credential exists, the platform connects anonymously without adding authentication.
* **Multiple vaults matching the same server URL**: Evaluated in the order vaults appear in `resources`; the first matching vault takes precedence.

For `mcp_oauth` credentials with refresh configuration, the platform automatically refreshes expired access tokens without manual intervention (credentials created via OAuth Connect include refresh configuration automatically whenever the provider issues a refresh token).

```bash cURL theme={null}
curl -X POST https://api.moonshot.ai/v1/sessions \
  -H "Authorization: Bearer $KIMI_API_KEY" \
  -H "kimi-api-version: 2026-09-01-beta" \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "agent_your_agent_id",
    "environment_id": "env_your_environment_id",
    "resources": [
      { "type": "vault", "vault_id": "vlt_your_vault_id" }
    ],
    "title": "Organize weekly tasks"
  }'
```

```bash CLI theme={null}
kha sessions create --file - <<'JSON'
{
  "agent_id": "agent_your_agent_id",
  "environment_id": "env_your_environment_id",
  "resources": [
    { "type": "vault", "vault_id": "vlt_your_vault_id" }
  ],
  "title": "Organize weekly tasks"
}
JSON
```

Use the `id` returned when creating your agent as `agent_id`, and obtain `environment_id` and `vault_id` from the creation responses for your execution environment and vault.

Vaults can only be bound when creating a session and cannot be added later, but you can unbind a vault via the session resources endpoints. Credential rotation and archival take effect automatically for existing sessions—the platform re-resolves credentials each time it establishes a connection, picking up updated values by the next connection without recreating the session.

For creating and managing credentials, see [Vaults](https://platform.kimi.ai/docs/hosted-agents/vaults.md); for `resources` binding details, see [Create a Session](https://platform.kimi.ai/docs/hosted-agents/sessions.md).

## MCP OAuth Connect authorization

If an MCP server uses OAuth 2.0, end users do not need to copy tokens manually. The platform provides **MCP OAuth Connect**: it guides the end user through the standard OAuth authorization code flow and stores the resulting token directly as a vault credential, so plaintext tokens never pass through your application.

You can initiate authorization in two ways:

> [card] [Console Connect](https://platform.kimi.ai/docs/hosted-agents/console.md)
>
> Click Connect on the Vaults or Plugins page in the console and follow the prompt to authorize; tokens are saved to the vault automatically.

> [card] [OAuth Session API](https://platform.kimi.ai/docs/hosted-agents/vaults.md)
>
> Call `POST /v1/vaults/{vault_id}/oauth-sessions` to start authorization, redirect the user to the consent page, and poll the result—ideal for embedding into your own product UI.

Credentials created via OAuth Connect behave identically to manually created `mcp_oauth` credentials, with the same URL-based matching and platform-managed token refresh. Starting a new flow when an active credential already exists for the same vault and server URL returns `409`; archive the existing credential first to re-authorize.

For the full API workflow and field reference, see the MCP OAuth Connect section in [Vaults](https://platform.kimi.ai/docs/hosted-agents/vaults.md).

## Runtime behavior and considerations

### Connection lifecycle

MCP connections follow the session's execution cycle: each time a session wakes up to run a task, the platform connects to every declared server, fetches the latest tool list, and closes the connections once execution finishes. As a result:

* Credential rotations and server-side tool list updates take effect no later than the next wakeup.
* Establishing connections on wakeup adds minor connection overhead, though connections to multiple MCP servers are established in parallel.

### Connection failures and graceful degradation

An unavailable MCP server **does not fail the session**—the platform degrades gracefully per server:

| Failure scenario | Behavior |
| - | - |
| Connection failure, initialization timeout, or authentication rejection | All tools from that server are skipped and hidden from the model for the current turn, while the session and other tools continue unaffected; the platform reconnects automatically on the next wakeup |
| Connection drop or timeout during a tool call | Returned to the model as a tool error result so the model can retry or adjust its approach; the session is not interrupted |
| No matching credential in bound vaults | Connects anonymously (valid configuration; no error raised) |

> [!WARNING]
>
> When an MCP server is unavailable, the model treats those capabilities as absent during that execution turn. If your workflow depends on a mission-critical MCP server, monitor session outputs in your application to verify expected behavior.

### Network access

If the session's [Execution Environment](https://platform.kimi.ai/docs/hosted-agents/environments.md) uses a `limited` network policy, enable `allow_mcp_servers` (or add the server domain to `allowed_hosts`) so MCP connections can reach the server endpoint.

## Next steps

> [card] [Inject MCP credentials](https://platform.kimi.ai/docs/hosted-agents/vaults.md)
>
> Create credentials, run OAuth Connect flows, and rotate or archive secrets.

> [card] [Configure tools and permissions](https://platform.kimi.ai/docs/hosted-agents/tools.md)
>
> Combine built-in toolsets with MCP tools.

> [card] [Set tool permissions](https://platform.kimi.ai/docs/hosted-agents/permissions.md)
>
> Configure per-tool permission policies to gate high-risk MCP tools.

> [card] [Allow MCP network access](https://platform.kimi.ai/docs/hosted-agents/environments.md)
>
> Configure network policies to allow outbound traffic to MCP endpoints.

> [card] [Start a session with MCP tools](https://platform.kimi.ai/docs/hosted-agents/sessions.md)
>
> Create a session and bind vaults in `resources`.
