Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
c570479
add working mcp integration
ryanhoangt Sep 4, 2025
f919824
migrate mcp tests
ryanhoangt Sep 4, 2025
5cc25c2
Merge branch 'main' into ht/migrate-mcp-clients
xingyaoww Sep 5, 2025
6b26b6b
fix example
ryanhoangt Sep 5, 2025
0c2693a
update api to sync
ryanhoangt Sep 5, 2025
c41bac5
update tests
ryanhoangt Sep 5, 2025
abdab20
improve thread-safety and resource management
ryanhoangt Sep 5, 2025
ee5291d
make mcp tool prints in xml format
xingyaoww Sep 5, 2025
29cbf41
make TextContent and ImageContent inherit from mcp types
xingyaoww Sep 5, 2025
09d3220
Merge commit 'b1627e7c972799f4ab048822c8f8420dda9f72dd' into ht/migra…
xingyaoww Sep 5, 2025
6ba785b
completely get rid of mcp config
xingyaoww Sep 5, 2025
c141f72
refactor to make agent_observation to return list[TextContent | Image…
xingyaoww Sep 5, 2025
0d07c60
add async utils
xingyaoww Sep 5, 2025
a16743a
fix microagent validation
xingyaoww Sep 5, 2025
47a6657
improve visualization for available tools
xingyaoww Sep 5, 2025
6b8c128
move security_risk to ActionBase
xingyaoww Sep 5, 2025
0a4aaba
refactor of MCP to keep MCPClient from fastmcp
xingyaoww Sep 5, 2025
8cc48a5
finally got everything working!
xingyaoww Sep 5, 2025
4108ce9
fix tests related to .agent_observation
xingyaoww Sep 5, 2025
581154c
remove mcp config tests
ryanhoangt Sep 5, 2025
6546117
fix tests
ryanhoangt Sep 5, 2025
991f93f
define a MCPActionBase to make a special case for MCP
xingyaoww Sep 5, 2025
7df9459
modify readme
xingyaoww Sep 5, 2025
04e2cfb
Fix failing tests after base class definition changes
openhands-agent Sep 5, 2025
37169ac
Merge commit '04e2cfb0737bd7318315e59d142d4511c8b87764' into ht/migra…
xingyaoww Sep 5, 2025
694d82c
Revert "Fix failing tests after base class definition changes"
xingyaoww Sep 5, 2025
1016eaa
make validation error clearer
xingyaoww Sep 5, 2025
cba94b9
add notion example
xingyaoww Sep 5, 2025
ac20b1f
fix all tests
xingyaoww Sep 5, 2025
3924556
Merge commit '09ec53252516e0a5c35a62ef54fe12d1ba7214f3' into ht/migra…
xingyaoww Sep 5, 2025
e27d425
fix all tests
xingyaoww Sep 5, 2025
f801d04
remove config folder
xingyaoww Sep 5, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ A clean, modular SDK for building AI agents with OpenHands. This project represe
## Project Overview

The OpenHands Agent SDK provides a streamlined framework for creating AI agents that can interact with tools, manage conversations, and integrate with various LLM providers.

## Repository Structure

```
```plain
agent-sdk/
├── Makefile # Build and development commands
├── pyproject.toml # Workspace configuration
Expand Down Expand Up @@ -102,7 +103,7 @@ conversation.run()

### Agents

Agents are the central orchestrators that coordinate between LLMs, tools, and conversations:
Agents are the central orchestrators that coordinate between LLMs and tools:

```python
from openhands.sdk import Agent, LLM
Expand Down Expand Up @@ -142,6 +143,7 @@ Tools provide agents with capabilities to interact with the environment:
#### Simplified Pattern (Recommended)

```python
from openhands.sdk import TextContent, ImageContent
from openhands.tools import BashTool, FileEditorTool

# Direct instantiation with simplified API
Expand Down Expand Up @@ -182,8 +184,8 @@ class GrepObservation(ObservationBase):
output: str = Field(default='')

@property
def agent_observation(self) -> str:
return self.output
def agent_observation(self) -> list[TextContent | ImageContent]:
return TextContent(text=self.output)

# --- Executor ---
class GrepExecutor(ToolExecutor[GrepAction, GrepObservation]):
Expand Down Expand Up @@ -229,6 +231,7 @@ conversation.run()
The context system manages agent state, environment, and conversation history.

Context is automatically managed but you can customize your context with:

1. [Repo Microagents](https://docs.all-hands.dev/usage/prompting/microagents-repo) that provide agent with context of your repository.
2. [Knowledge Microagents](https://docs.all-hands.dev/usage/prompting/microagents-keyword) that provide agent with context when user mentioned certain keywords
3. Providing custom suffix for system and user prompt.
Expand Down
10 changes: 6 additions & 4 deletions examples/2_custom_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
Agent,
Conversation,
EventType,
ImageContent,
LLMConvertibleEvent,
Message,
TextContent,
Expand Down Expand Up @@ -47,17 +48,18 @@ class GrepObservation(ObservationBase):
count: int = 0

@property
def agent_observation(self) -> str:
def agent_observation(self) -> list[TextContent | ImageContent]:
if not self.count:
return "No matches found."
return [TextContent(text="No matches found.")]
files_list = "\n".join(f"- {f}" for f in self.files[:20])
sample = "\n".join(self.matches[:10])
more = "\n..." if self.count > 10 else ""
return (
ret = (
f"Found {self.count} matching lines.\n"
f"Files:\n{files_list}\n"
f"Sample:\n{sample}{more}"
)
return [TextContent(text=ret)]


# --- Executor ---
Expand All @@ -79,7 +81,7 @@ def __call__(self, action: GrepAction) -> GrepObservation:
else:
cmd = f"grep -rHnE {pat} {root_q} 2>/dev/null | head -100"

result = self.bash(ExecuteBashAction(command=cmd, security_risk="LOW"))
result = self.bash(ExecuteBashAction(command=cmd))

matches: list[str] = []
files: set[str] = set()
Expand Down
81 changes: 81 additions & 0 deletions examples/7_mcp_integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import os

from pydantic import SecretStr

from openhands.sdk import (
LLM,
Agent,
Conversation,
EventType,
LLMConvertibleEvent,
Message,
TextContent,
Tool,
create_mcp_tools,
get_logger,
)
from openhands.tools import BashTool, FileEditorTool


logger = get_logger(__name__)

# Configure LLM
api_key = os.getenv("LITELLM_API_KEY")
assert api_key is not None, "LITELLM_API_KEY environment variable is not set."
llm = LLM(
model="litellm_proxy/anthropic/claude-sonnet-4-20250514",
base_url="https://llm-proxy.eval.all-hands.dev",
api_key=SecretStr(api_key),
)

cwd = os.getcwd()
tools: list[Tool] = [
BashTool(working_dir=cwd),
FileEditorTool(),
]

# Add MCP Tools
mcp_config = {"mcpServers": {"fetch": {"command": "uvx", "args": ["mcp-server-fetch"]}}}
mcp_tools = create_mcp_tools(mcp_config, timeout=30)
tools.extend(mcp_tools)
logger.info(f"Added {len(mcp_tools)} MCP tools")
for tool in mcp_tools:
logger.info(f" - {tool.name}: {tool.description}")


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

llm_messages = [] # collect raw LLM messages


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


# Conversation
conversation = Conversation(
agent=agent,
callbacks=[conversation_callback],
)

# Example message that can use MCP tools if available
message = Message(
role="user",
content=[
TextContent(
text="Read https://github.com/All-Hands-AI/OpenHands and "
+ "write 3 facts about the project into FACTS.txt."
)
],
)

logger.info("Starting conversation with MCP integration...")
response = conversation.send_message(message)
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]}")
78 changes: 78 additions & 0 deletions examples/8_mcp_with_oauth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import os

from pydantic import SecretStr

from openhands.sdk import (
LLM,
Agent,
Conversation,
EventType,
LLMConvertibleEvent,
Message,
TextContent,
Tool,
create_mcp_tools,
get_logger,
)
from openhands.tools import BashTool, FileEditorTool


logger = get_logger(__name__)

# Configure LLM
api_key = os.getenv("LITELLM_API_KEY")
assert api_key is not None, "LITELLM_API_KEY environment variable is not set."
llm = LLM(
model="litellm_proxy/anthropic/claude-sonnet-4-20250514",
base_url="https://llm-proxy.eval.all-hands.dev",
api_key=SecretStr(api_key),
)

cwd = os.getcwd()
tools: list[Tool] = [
BashTool(working_dir=cwd),
FileEditorTool(),
]

# Add MCP Tools
mcp_config = {
"mcpServers": {"Notion": {"url": "https://mcp.notion.com/mcp", "auth": "oauth"}}
}
mcp_tools = create_mcp_tools(mcp_config, timeout=30)
tools.extend(mcp_tools)
logger.info(f"Added {len(mcp_tools)} MCP tools")
for tool in mcp_tools:
logger.info(f" - {tool.name}: {tool.description}")


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

llm_messages = [] # collect raw LLM messages


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


# Conversation
conversation = Conversation(
agent=agent,
callbacks=[conversation_callback],
)

# Example message that can use MCP tools if available
message = Message(
role="user",
content=[TextContent(text="Summarize my notion workspace.")],
)

logger.info("Starting conversation with MCP integration...")
response = conversation.send_message(message)
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]}")
6 changes: 4 additions & 2 deletions openhands/sdk/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from importlib.metadata import PackageNotFoundError, version

from openhands.sdk.agent import Agent, AgentBase
from openhands.sdk.config import MCPConfig
from openhands.sdk.context import AgentContext
from openhands.sdk.conversation import Conversation, ConversationCallbackType
from openhands.sdk.event import EventBase, EventType, LLMConvertibleEvent
Expand All @@ -14,6 +13,7 @@
TextContent,
)
from openhands.sdk.logger import get_logger
from openhands.sdk.mcp import MCPClient, MCPTool, create_mcp_tools
from openhands.sdk.tool import ActionBase, ObservationBase, Tool


Expand All @@ -34,7 +34,9 @@
"Agent",
"ActionBase",
"ObservationBase",
"MCPConfig",
"MCPClient",
"MCPTool",
"create_mcp_tools",
"get_logger",
"Conversation",
"ConversationCallbackType",
Expand Down
4 changes: 0 additions & 4 deletions openhands/sdk/config/__init__.py

This file was deleted.

Loading