Claude agent sdk adapter #1
Open
Lighthousexx wants to merge 7 commits intomainfrom
Open
Conversation
This commit implements a comprehensive adapter for integrating Anthropic's Claude Agent SDK with AgentScope Runtime, enabling Claude-powered agents to leverage AgentScope Runtime's infrastructure. ## Components Implemented 1. **Message Format Conversion** (message.py) - Bidirectional conversion between Claude SDK and Runtime formats - Supports text, tool_use, and tool_result blocks - Handles multiple content types and message grouping 2. **Streaming Adapter** (stream.py) - Real-time message streaming with delta updates - Proper handling of in-progress and completed states - Tool call streaming support 3. **Memory Management** (memory.py) - In-memory conversation history storage - Session isolation by (user_id, session_id) - Simple API for adding/retrieving messages 4. **State Management** (state.py) - Agent state persistence and recovery - Session resumption via claude_session_id - JSON export/import support 5. **Demo Application** (examples/integrations/claude/) - Complete working example with simulation mode - Session management endpoints - Integration pattern documentation 6. **Comprehensive Tests** (tests/test_claude_agent_adapter.py) - Message conversion tests - Memory isolation tests - State persistence tests - All core tests passing (8/8) ## Features - Multi-user, multi-session support - Message format conversion - Streaming support - Conversation history persistence - State save/restore - Session isolation - Comprehensive documentation ## Testing Core functionality verified with standalone tests: - Memory adapter: 4/4 tests passed - State adapter: 4/4 tests passed https://claude.ai/code/session_01BDTTkUe4sw9pb6xMNkRwik
Add comprehensive summary document covering: - Complete implementation details - File structure and statistics - Test results (8/8 passing) - Usage examples and next steps - Architecture overview https://claude.ai/code/session_01BDTTkUe4sw9pb6xMNkRwik
This commit implements comprehensive tool support for the Claude Agent SDK
adapter, enabling AgentScope Runtime tools to be used with Claude agents
via MCP (Model Context Protocol).
## Components Implemented
1. **Tool Adapter** (tool/tool.py)
- ClaudeToolAdapter class for wrapping Runtime tools
- Automatic schema extraction from Pydantic models
- Callable generation for MCP servers
- Input validation and error handling
- Support for tool name/description overrides
2. **Tool Utilities**
- claude_tool_adapter() - Single tool conversion
- create_claude_toolkit() - Batch tool conversion
- create_claude_mcp_server_config() - MCP server config generation
- get_allowed_tool_names() - Tool name formatting for Claude SDK
3. **Demo Application** (examples/claude_with_tools_demo.py)
- Complete example with custom Calculator and Weather tools
- MCP server configuration demonstration
- Direct tool execution API endpoints
- Production integration pattern
4. **Comprehensive Tests** (tests/test_claude_tool_adapter.py)
- Tool adapter creation and schema extraction
- Callable function generation and execution
- Toolkit and MCP server config creation
- Name overrides and validation
- Error handling verification
5. **Updated Documentation** (README.md)
- Tool integration guide added to features
- Complete usage examples for all tool APIs
- Custom tool creation tutorial
- Schema auto-generation explanation
- Extended API reference with tool methods
## Features
- ✅ Convert Runtime tools to Claude SDK MCP format
- ✅ Auto-extract schemas from Pydantic models
- ✅ Generate async callables for MCP servers
- ✅ Support tool name/description overrides
- ✅ Batch tool conversion utilities
- ✅ MCP server configuration builder
- ✅ Proper error handling and validation
- ✅ Full type hints and documentation
## Tool Schema Auto-Generation
Input schemas are automatically generated from Pydantic BaseModel:
- Type mapping (str→string, int→integer, etc.)
- Required field detection
- Description extraction from Field()
- Support for nested objects and arrays
- Enum and default value handling
## Integration Pattern
```python
from agentscope_runtime.tools import MyTool
from agentscope_runtime.adapters.claude.tool import create_claude_mcp_server_config
# Create MCP config
config = create_claude_mcp_server_config([MyTool()])
# With Claude SDK:
# mcp_server = create_sdk_mcp_server(...)
# options = ClaudeAgentOptions(mcp_servers={...}, allowed_tools=[...])
```
## Examples
- Simple calculator and weather tools
- Direct tool execution endpoints
- MCP server configuration
- Integration with Claude SDK pattern
https://claude.ai/code/session_01BDTTkUe4sw9pb6xMNkRwik
This commit implements Claude Agent SDK style @tool decorator for defining tools, providing a familiar pattern for Claude SDK users. ## Components Implemented 1. **Native @tool Decorator** (claude_native_tool.py) - Decorator supporting both @tool and @tool(...) patterns - Automatic schema generation from type hints - Automatic name/description extraction from function - Async callable wrapper with error handling - Functions remain directly callable after decoration 2. **Utility Functions** - create_claude_native_tool() - Create tool from function - extract_tools_from_module() - Extract all @tool from module - create_mcp_server_from_decorated_tools() - MCP server config - get_allowed_tool_names_from_decorated() - Tool name formatting 3. **Demo Application** (claude_native_tools_demo.py) - 4 example tools using @tool decorator: * calculator - Arithmetic operations * get_current_weather - Weather lookup * string_reverse - String reversal * fibonacci - Fibonacci sequence - Direct tool execution API - Demo endpoint showing all tools in action 4. **Comprehensive Tests** (test_claude_native_tool_decorator.py) - Decorator with/without parameters - Auto schema generation - Tool execution and error handling - MCP server configuration - All 13 test cases passing ## Features ✅ Two decorator usage patterns: - @tool (without parameters - auto inference) - @tool(name="...", description="...") (with parameters) ✅ Automatic schema generation from type hints: - str → "string", int → "integer", etc. - Detects required vs optional parameters - Supports List, Dict, bool types ✅ Auto-extraction from function: - Name from function name - Description from docstring - Schema from type hints ✅ Decorated functions remain callable: - Can call normally: await my_tool(a, b) - Or via MCP callable: await tool_config["callable"]({"a": 1, "b": 2}) ## Usage Examples Simple decorator without parameters: ```python @tool async def calculate(operation: str, a: float, b: float) -> dict: '''Perform arithmetic operations.''' return {"result": a + b if operation == "add" else a - b} # Auto-generated: # - name: "calculate" # - description: "Perform arithmetic operations." # - schema: from type hints ``` Decorator with parameters: ```python @tool(name="search", description="Search the web") async def web_search(query: str, limit: int = 10) -> dict: return {"results": [...]} ``` Create MCP server: ```python config = create_mcp_server_from_decorated_tools( [calculate, web_search], server_name="my-tools", ) # With Claude SDK: # mcp_server = create_sdk_mcp_server( # name=config["server_name"], # tools=[t["callable"] for t in config["tools"]], # ) ``` ## Testing All 13 test cases pass: - Decorator patterns (with/without params) - Schema generation - Tool execution - Error handling - MCP server config - Default parameter values Run tests: ```bash pytest tests/test_claude_native_tool_decorator.py -v ``` Run demo: ```bash python examples/integrations/claude/claude_native_tools_demo.py # Test a tool: curl -X POST http://127.0.0.1:8092/api/tools/calculator/execute \ -H "Content-Type: application/json" \ -d '{"operation": "multiply", "a": 7, "b": 6}' ``` https://claude.ai/code/session_01BDTTkUe4sw9pb6xMNkRwik
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
[Describe what this PR does and why]
Related Issue: Fixes #[issue_number] or Relates to #[issue_number]
Security Considerations: [If applicable, especially for sandbox changes]
Type of Change
Component(s) Affected
Checklist
Testing
[How to test these changes]
Additional Notes
[Optional: any other context]