Agent Skills 与上下文工程(2/3)

This page outlines how to configure and use the Model Context Protocol (MCP) in OpenHands, allowing you to extend the agent's capabilities with custom tools.

Overview

Model Context Protocol (MCP) is a mechanism that allows OpenHands to communicate with external tool servers. These servers can provide additional functionality to the agent, such as specialized data processing, external API access, or custom tools. MCP is based on the open standard defined at modelcontextprotocol.io.

Supported MCPs

OpenHands supports the following MCP transport protocols:

How MCP Works

When a conversation starts, OpenHands:

  1. Reads the MCP servers you have configured and enabled.
  2. Connects to any configured SSE and SHTTP servers.
  3. Starts any configured stdio servers.
  4. Registers the tools provided by these servers with the agent.

The agent can then use these tools just like any built-in tool. When the agent calls an MCP tool:

  1. OpenHands routes the call to the appropriate MCP server.
  2. The server processes the request and returns a response.
  3. OpenHands converts the response to an observation and presents it to the agent.

Servers you add or change apply to new conversations, not to conversations that are already running.

Configuration

Where you configure MCP servers depends on how you run OpenHands:

  • Agent Canvas (local or connected to OpenHands Cloud): Customize > MCP Servers. See Add a Custom Server.
  • CLI: openhands mcp add, which writes ~/.openhands/mcp.json. See CLI MCP Servers.
  • SDK: pass mcp_config to your agent. See the SDK MCP Guide.

Current OpenHands releases don't read MCP servers from a config.toml [mcp] section (sse_servers, shttp_servers, stdio_servers). That format belongs to legacy OpenHands (V0). If you still have one, add those servers again using one of the options above. The legacy format is kept for reference in the V0 configuration options.

Add a Custom Server

To add a server that isn't in the Marketplace:

  1. In Agent Canvas, open Customize > MCP Servers.
  2. Click Add custom server.
  3. Choose a Server Type and fill in the fields for that type (see below).
  4. Click Test connection. A working server reports how many tools it provides.
  5. Save the server. New conversations can use its tools.

On a local backend, Agent Canvas saves MCP servers in its settings store (by default ~/.openhands/settings.json) with credentials encrypted. Manage servers from Customize > MCP Servers rather than editing that file. There is no per-project MCP configuration file.

Server Fields

Streamable HTTP is the recommended transport for remote servers.

* `Server name`: A name for the server.
* `URL` (required): The server's endpoint, starting with `http://` or `https://`.
* `Authentication`: How OpenHands authenticates to the server.
  * `None`: No credentials.
  * `Bearer token`: Enter the token in `API Key`. OpenHands sends `Authorization: Bearer <token>`.
  * `Header`: Enter custom headers in `Headers`, one `NAME=value` per line (for example, `X-API-Key=value`).
  * `OAuth`: See [OAuth Authentication](#oauth-authentication).
* `Timeout (seconds)` (optional): How long to wait for the server before timing out. Use a longer timeout for
  servers whose tools run heavy operations such as large file processing.



Server-Sent Events is an older transport for remote servers. Use it only if the server doesn't support SHTTP.

* `Server name`: A name for the server.
* `URL` (required): The server's SSE endpoint.
* `Authentication`: The same options as SHTTP.




  While stdio servers are supported, [we recommend using MCP proxies](#configuration-examples) for
  better reliability and performance.


* `Name` (required): A unique name for the server. Accepted characters are letters, digits, underscores (`_`),
  and hyphens (`-`). For example, `integrations-hub` is a valid name.
* `Command` (required): The command to run the server, such as `npx` or `uvx`.
* `Command Arguments` (optional): One argument per line, passed to the command in order.
* `Environment Variables` (optional): One `KEY=value` per line, set for the server process.

When to Use Direct Stdio

Direct stdio connections may still be appropriate in these scenarios:

  • Development and testing: Quick prototyping of MCP servers.
  • Simple, single-use tools: Tools that don't require high reliability or concurrent access.
  • Local-only environments: When you don't want to manage additional proxy processes.

Configuration Examples

For stdio-based MCP servers, we recommend using MCP proxy tools like
[`supergateway`](https://github.com/supercorp-ai/supergateway) instead of direct stdio connections.
[SuperGateway](https://github.com/supercorp-ai/supergateway) is a popular MCP proxy that converts stdio MCP servers to
HTTP/SSE endpoints.

Start the proxy servers separately:
# Terminal 1: Filesystem server proxy
supergateway --stdio "npx @modelcontextprotocol/server-filesystem /" --port 8080

# Terminal 2: Fetch server proxy
supergateway --stdio "uvx mcp-server-fetch" --port 8081
Then add each proxy with `Add custom server`:

| Field | Filesystem proxy | Fetch proxy |
| - | - | - |
| `Server Type` | `SSE` | `SSE` |
| `Server name` | `filesystem` | `fetch` |
| `URL` | `http://localhost:8080/sse` | `http://localhost:8081/sse` |
| `Authentication` | `None` | `None` |


  `localhost` works when the agent server runs on the same machine as the proxy. If your conversations run in
  Docker or a remote sandbox, use an address that environment can reach.





  This setup is not recommended for production.


Add the server with `Add custom server`:

| Field | Value |
| - | - |
| `Server Type` | `STDIO` |
| `Name` | `fetch` |
| `Command` | `uvx` |
| `Command Arguments` | `mcp-server-fetch` |

For production use, we recommend using proxy tools like SuperGateway.

Other options include:

  • Custom FastAPI/Express servers: Build your own HTTP wrapper around stdio MCP servers.
  • Docker-based proxies: Containerized solutions for better isolation.
  • Cloud-hosted MCP services: Third-party services that provide MCP endpoints.

Documenting an Integration for OpenHands

If you maintain an MCP server and want to publish setup steps for OpenHands users:

  • For Agent Canvas, give the Add custom server values: Server Type, then URL and Authentication (SSE/SHTTP) or Name, Command, Command Arguments, and Environment Variables (STDIO).
  • For the CLI, give the openhands mcp add command. See CLI MCP Servers.
  • Don't write a config.toml [mcp] section. Current OpenHands releases ignore it.
  • To give the agent standing instructions (for example, when to call your tools), add them to the repository's AGENTS.md. OpenHands loads it into the agent's context. See Repository Skills.

Manage Installed Servers

In Agent Canvas, open Customize > MCP Servers to manage installed MCP servers. Use the control on an installed server card to disable it without deleting its configuration or saved credentials. Disabled servers are unavailable to new conversations until you enable them again.

Adding, editing, renaming, or deleting one server does not remove saved credentials for your other servers. Use the editor's delete action only when you want to remove that server configuration. Editing a disabled server does not enable it.

OAuth Authentication

Some MCP servers (like Notion MCP) require OAuth authentication instead of API keys. OpenHands supports OAuth-based MCP servers through the FastMCP library.

How OAuth Works

When you configure an OAuth-enabled MCP server:

  1. First connection: When the agent first attempts to use tools from an OAuth-protected MCP server, OpenHands initiates the OAuth flow
  2. Browser authentication: A browser window opens automatically for you to authorize access
  3. Token storage: After authorization, tokens are securely stored locally in ~/.fastmcp/oauth-mcp-client-cache/
  4. Automatic refresh: FastMCP automatically refreshes tokens as needed

On OpenHands Cloud, saving MCP settings keeps the OAuth credential and its token state instead of flattening it into a request header, so installed servers keep their authorization across saves. When a server already holds working tokens, OpenHands probes them and skips the consent prompt; the browser window only opens when authorization is actually required.

Configuration

Servers in the `Marketplace` that use OAuth, such as Notion, start the authorization flow when you install them.

For a custom server, click `Add custom server`, choose `SHTTP` or `SSE`, and set `Authentication` to `OAuth`.
Fill in `OAuth client ID`, `OAuth client secret`, and `OAuth scopes` if the server requires them.



Use the `--auth oauth` flag when adding an MCP server:
openhands mcp add notion --transport http \
  --auth oauth \
  https://mcp.notion.com/mcp
This creates a configuration in `~/.openhands/mcp.json`:
{
  "mcpServers": {
    "notion": {
      "url": "https://mcp.notion.com/mcp",
      "transport": "http",
      "auth": "oauth"
    }
  }
}
Configure OAuth in your `mcp_config`:
mcp_config = {
    "mcpServers": {
        "notion": {
            "url": "https://mcp.notion.com/mcp",
            "auth": "oauth"
        }
    }
}
agent = Agent(llm=llm, tools=tools, mcp_config=mcp_config)
See the [SDK MCP Guide](https://docs.openhands.dev/sdk/guides/mcp) for complete examples.

OAuth MCP servers require user interaction for the initial authentication. This means they may not be suitable for fully automated/headless workflows. For automation, consider using API key-based authentication where available.


Manage repository, organization, and user skills and control how plugins are discovered and loaded in OpenHands Enterprise.

OpenHands Enterprise supports several ways to add reusable guidance and capabilities to conversations. Choose the approach that meets your needs.

This guide covers Enterprise distribution and governance. For skill formats, triggers, and precedence, see Skills. For plugin structure and development, see Plugins.

Choose a Distribution Method

Method Scope Use When
AGENTS.md One repository Instructions should apply whenever OpenHands works in the repository
.agents/skills/ One repository A focused workflow or reference should load on demand
Organization skills repository Organization Standards should be available across the organization's conversations
User skills repository One user A skill should follow one user across conversations
Conversation plugin One conversation A capability bundle is needed for a specific task
Marketplace User or organization Users need a governed collection of plugins they can load on demand
Marketplace Auto-Load User or organization Every applicable conversation requires the marketplace's plugins

Understand Enterprise Loading Layers

Enterprise marketplaces operate at three different layers:

  1. Instance Plugin Marketplace — An administrator configures the catalog source through Replicated or Helm. This powers the Plugin Directory at /plugins.
  2. Registered marketplace — A user or organization registers a Git repository under Settings > Skills. Registration makes its plugins discoverable and governable.
  3. Conversation attachment — A plugin is loaded into a conversation through the Plugin Directory, a launch link, the V1 API, or Auto-Load.

Registering a marketplace does not by itself load every plugin into every conversation.

Add Repository Skills

Use repository files when a skill or instruction belongs to one codebase.

Permanent Repository Context

Add AGENTS.md at the repository root for concise instructions that should always apply:

my-project/
└── AGENTS.md

OpenHands loads this file when a conversation uses the repository.

On-Demand Repository Skills

Add one directory per skill under .agents/skills/:

my-project/
└── .agents/
    └── skills/
        └── deploy-helper/
            ├── SKILL.md
            ├── scripts/
            └── references/

The SKILL.md file contains the skill name, description, and instructions. OpenHands initially shows the agent a summary and loads the full content when the skill is invoked or triggered.

See Skills for the complete format and loading precedence.

Add Organization and User Skills

Use a special configuration repository when skills should apply beyond one project.

For GitHub, create a repository named .agents under the organization or user and place skills under skills/:

Great-Co/.agents
└── skills/
    └── engineering-standards/
        └── SKILL.md

For GitLab organizations, use openhands-config because GitLab repository names cannot begin with a period.

Earlier OpenHands Enterprise releases may use a .openhands configuration repository. If an existing deployment already uses .openhands, confirm the supported convention for that release before migrating. Do not define duplicate skill names in both repositories.

The source control integration must have access to the configuration repository. Access to one user or organization does not grant access to repositories owned by another organization.

See Organization and User Skills for more information.

Register a Marketplace

Register a marketplace to make a Git-hosted plugin collection available to a user or organization.

  1. Open Settings > Skills.
  2. In Marketplaces, select + Add Repository.
  3. Enter the repository URL.
  4. Optionally specify a branch, tag, commit, or repository path.
  5. Select the personal or organization scope available to your role.
  6. Save the marketplace.

The Skills & Plugins table shows the entries discovered from registered marketplaces and built-in sources.

Register only repositories you trust. A loaded plugin can include skills, hooks, MCP servers, agents, and commands. It can also use secrets available to the conversation. Explicit launch flows require trust confirmation. Review every plugin before enabling Auto-Load, which may attach plugins without a per-conversation prompt.

For private repositories, ensure that your Enterprise source control integration has access.

Load a Plugin for One Conversation

Use explicit attachment when a plugin is needed for one task. This keeps ordinary conversations isolated from unrelated plugin context and integrations.

1. Open `https://app.<your-base-domain>/plugins`.
2. Select a plugin.
3. Select `Create New Conversation`.
4. Review the repository, path, and ref.
5. Confirm that you trust the plugin.
6. Select `Start Conversation`.

The plugin is loaded only into the new conversation.



Use the `/launch` route to share a preconfigured plugin:
https://app.<your-base-domain>/launch?plugins=<base64-encoded-plugin-array>
A launch link can include multiple plugins, editable parameter defaults, and an optional
starting message. The user reviews the configuration and confirms trust before the
conversation starts.

See [Plugin Launcher](https://docs.openhands.dev/openhands/usage/cloud/plugin-launcher) for the plugin definition and
encoding format. Replace the Cloud hostname in its examples with your Enterprise application
hostname.



Add a `plugins` array to `POST /api/v1/app-conversations`:
{
  "initial_message": {
    "content": [
      {
        "type": "text",
        "text": "Run the release readiness check."
      }
    ]
  },
  "plugins": [
    {
      "source": "github:AcmeCo/openhands-plugins",
      "ref": "main",
      "repo_path": "plugins/release-ready"
    }
  ]
}
See [Cloud API](https://docs.openhands.dev/openhands/usage/cloud/cloud-api) for authentication, response handling, and
conversation status. Use your Enterprise application hostname as the base URL.

Configure Auto-Load

Auto-Load adds a registered marketplace's plugins to every applicable conversation in its scope.

Use Auto-Load when:

  • Every conversation requires the capability.
  • The marketplace is controlled and reviewed by your organization.
  • The additional context and startup work are acceptable.
  • The plugins are allowed to use the secrets available in those conversations.

Keep Auto-Load off when users should choose plugins per task.

To change Auto-Load:

  1. Open Settings > Skills.
  2. Find the marketplace under Marketplaces.
  3. Toggle Auto-Load.
  4. Save the changes.
  5. Start a new conversation to verify the new behavior.

Changes do not retroactively reload skills or plugins in an already-running conversation.

Verify Skill and Plugin Loading

Use this to really verify loading instead of checking only that a name appears in the UI.

  1. Create a small skill with a unique trigger and an exact expected response.
  2. Start a new conversation in the intended scope.
  3. Use the trigger.
  4. Confirm that the response reflects the skill's instructions.
  5. Start a control conversation outside that scope and confirm that the skill does not activate.

For organization skills, use a conversation without a selected repository or explicit plugin when the release supports organization-wide loading in that context. For marketplace Auto-Load, compare a conversation created before the setting changed with a new conversation created afterward.

Troubleshooting

<AccordionGroup>

Registration makes plugins available on demand. Enable Auto-Load for the marketplace or attach
a plugin explicitly through the Plugin Directory, a launch link, or the V1 API.



Confirm that the conversation selected the expected repository and ref. Verify the skill path
is `.agents/skills/<name>/SKILL.md` and that the source control integration can clone the
repository.



Skill enablement is based on the skill name, not its source. Disabling a built-in skill also
disables a custom skill with the same `name` in its `SKILL.md` frontmatter. A custom skill name
should not conflict with a built-in skill name. Rename the custom skill and its parent directory
to a unique name, such as `acme-github`.



Confirm that its trigger matches the user message or explicitly ask the agent to invoke the
skill. Test with a unique trigger and exact expected behavior.

</AccordionGroup>

Next Steps

Learn about skill formats, triggers, and loading precedence.



Build bundles containing skills, hooks, MCP servers, agents, and commands.



Enable and configure the Enterprise Plugin Directory.



Create shareable links that open conversations with plugins attached.

Manage agent memory by condensing conversation history to save tokens.

A ready-to-run example is available here!

What is a Context Condenser?

A context condenser is a crucial component that addresses one of the most persistent challenges in AI agent development: managing growing conversation context efficiently. As conversations with AI agents grow longer, the cumulative history leads to:

  • 💰 Increased API Costs: More tokens in the context means higher costs per API call
  • ⏱️ Slower Response Times: Larger contexts take longer to process
  • 📉 Reduced Effectiveness: LLMs become less effective when dealing with excessive irrelevant information

The context condenser solves this by intelligently summarizing older parts of the conversation while preserving essential information needed for the agent to continue working effectively.

Default Implementation: LLMSummarizingCondenser

OpenHands SDK provides LLMSummarizingCondenser as the default condenser implementation. This condenser uses an LLM to generate summaries of conversation history when it exceeds the configured size limit.

How It Works

When conversation history exceeds a defined threshold, the LLM-based condenser:

  1. Keeps recent messages intact - The most recent exchanges remain unchanged for immediate context
  2. Preserves key information - Important details like user goals, technical specifications, and critical files are retained
  3. Summarizes older content - Earlier parts of the conversation are condensed into concise summaries using LLM-generated summaries
  4. Maintains continuity - The agent retains awareness of past progress without processing every historical interaction

<img alt="Light mode interface" />

<img alt="Dark mode interface" />

This approach achieves remarkable efficiency gains:

  • Up to 2x reduction in per-turn API costs
  • Consistent response times even in long sessions
  • Equivalent or better performance on software engineering tasks

Learn more about the implementation and benchmarks in our blog post on context condensation.

Extensibility

The LLMSummarizingCondenser extends the RollingCondenser base class, which provides a framework for condensers that work with rolling conversation history. You can create custom condensers by extending base classes (source code):

  • RollingCondenser - For condensers that apply condensation to rolling history
  • CondenserBase - For more specialized condensation strategies

This architecture allows you to implement custom condensation logic tailored to your specific needs while leveraging the SDK's conversation management infrastructure.

Setting Up Condensing

Create a LLMSummarizingCondenser to manage the context. The condenser will automatically truncate conversation history when it exceeds max_size, and replaces the dropped events with an LLM-generated summary.

This condenser triggers when there are more than max_context_length events in the conversation history, and always keeps the first keep_first events (system prompts, initial user messages) to preserve important context.

from openhands.sdk.context import LLMSummarizingCondenser

condenser = LLMSummarizingCondenser(
    llm=llm.model_copy(update={"usage_id": "condenser"}), max_size=10, keep_first=2
)

# Agent with condenser
agent = Agent(llm=llm, tools=tools, condenser=condenser)

Ready-to-run example

This example is available on GitHub: examples/01_standalone_sdk/14_context_condenser.py

Automatically condense conversation history when context length exceeds limits, reducing token usage while preserving important information:

"""
To manage context in long-running conversations, the agent can use a context condenser
that keeps the conversation history within a specified size limit. This example
demonstrates using the `LLMSummarizingCondenser`, which automatically summarizes
older parts of the conversation when the history exceeds a defined threshold.
"""

import os

from pydantic import SecretStr

from openhands.sdk import (
    LLM,
    Agent,
    Conversation,
    Event,
    LLMConvertibleEvent,
    get_logger,
)
from openhands.sdk.context.condenser import LLMSummarizingCondenser
from openhands.sdk.tool import Tool
from openhands.tools.file_editor import FileEditorTool
from openhands.tools.task_tracker import TaskTrackerTool
from openhands.tools.terminal import TerminalTool

logger = get_logger(__name__)

# Configure LLM
api_key = os.getenv("LLM_API_KEY")
assert api_key is not None, "LLM_API_KEY environment variable is not set."
model = os.getenv("LLM_MODEL", "anthropic/claude-sonnet-4-5-20250929")
base_url = os.getenv("LLM_BASE_URL")
llm = LLM(
    usage_id="agent",
    model=model,
    base_url=base_url,
    api_key=SecretStr(api_key),
)

# Tools
cwd = os.getcwd()
tools = [
    Tool(
        name=TerminalTool.name,
    ),
    Tool(name=FileEditorTool.name),
    Tool(name=TaskTrackerTool.name),
]

# Create a condenser to manage the context. The condenser will automatically truncate
# conversation history when it exceeds max_size, and replaces the dropped events with an
#  LLM-generated summary. This condenser triggers when there are more than ten events in
# the conversation history, and always keeps the first two events (system prompts,
# initial user messages) to preserve important context.
condenser = LLMSummarizingCondenser(
    llm=llm.model_copy(update={"usage_id": "condenser"}), max_size=10, keep_first=2
)

# Agent with condenser
agent = Agent(llm=llm, tools=tools, condenser=condenser)

llm_messages = []  # collect raw LLM messages

def conversation_callback(event: Event):
    if isinstance(event, LLMConvertibleEvent):
        llm_messages.append(event.to_llm_message())

conversation = Conversation(
    agent=agent,
    callbacks=[conversation_callback],
    persistence_dir="./.conversations",
    workspace=".",
)

# Send multiple messages to demonstrate condensation
print("Sending multiple messages to demonstrate LLM Summarizing Condenser...")

conversation.send_message(
    "Hello! Can you create a Python file named math_utils.py with functions for "
    "basic arithmetic operations (add, subtract, multiply, divide)?"
)
conversation.run()

conversation.send_message(
    "Great! Now add a function to calculate the factorial of a number."
)
conversation.run()

conversation.send_message("Add a function to check if a number is prime.")
conversation.run()

conversation.send_message(
    "Add a function to calculate the greatest common divisor (GCD) of two numbers."
)
conversation.run()

conversation.send_message(
    "Now create a test file to verify all these functions work correctly."
)
conversation.run()

print("=" * 100)
print("Conversation finished. Got the following LLM messages:")
for i, message in enumerate(llm_messages):
    print(f"Message {i}: {str(message)[:200]}")

# Conversation persistence
print("Serializing conversation...")

del conversation

# Deserialize the conversation
print("Deserializing conversation...")
conversation = Conversation(
    agent=agent,
    callbacks=[conversation_callback],
    persistence_dir="./.conversations",
    workspace=".",
)

print("Sending message to deserialized conversation...")
conversation.send_message("Finally, clean up by deleting both files.")
conversation.run()

print("=" * 100)
print("Conversation finished with LLM Summarizing Condenser.")
print(f"Total LLM messages collected: {len(llm_messages)}")
print("\nThe condenser automatically summarized older conversation history")
print("when the conversation exceeded the configured max_size threshold.")
print("This helps manage context length while preserving important information.")

# Report cost
cost = conversation.conversation_stats.get_combined_metrics().accumulated_cost
print(f"EXAMPLE_COST: {cost}")

You can run the example code as-is.

The model name should follow the LiteLLM convention: provider/model_name (e.g., anthropic/claude-sonnet-4-5-20250929, openai/gpt-4o). The LLM_API_KEY should be the API key for your chosen provider.

ChatGPT Plus/Pro subscribers: You can use LLM.subscription_login() to authenticate with your ChatGPT account and access Codex models without consuming API credits. See the LLM Subscriptions guide for details.

Next Steps

  • LLM Metrics - Track token usage reduction and analyze cost savings