Skip to main content

Generic Claude agent gateway with MCP tool support and streaming

Project description

claude-gateway

A Python package for building streaming Claude agent applications with MCP (Model Context Protocol) tool support. Handles the agent loop, tool dispatch, MCP server management, and SSE event streaming — so you can focus on your domain logic.

Install

pip install claude-gateway

Quick Start

import asyncio
from claude_gateway import AgentRunner, EventLog, McpClientManager, ToolDispatcher

async def main():
    # 1. Set up MCP client (reads ~/.claude.json for server configs)
    mcp = McpClientManager(
        allowed_servers={"my-mcp-server"},
        builtin_tool_names=set(),
    )
    await mcp.startup()

    # 2. Create a tool dispatcher with local handlers + MCP tools
    async def my_tool(tool_input, *, call_index=0):
        return {"result": f"Hello from {tool_input.get('name', 'world')}"}, None

    dispatcher = ToolDispatcher(
        mcp_client=mcp,
        local_tool_handlers={"greet": my_tool},
    )

    # 3. Create event log for SSE streaming
    event_log = EventLog(session_id="session-001")

    # 4. Run the agent
    runner = AgentRunner(
        event_log=event_log,
        dispatcher=dispatcher,
        session_id="session-001",
        auth_config={"auth_mode": "api", "api_key": "sk-ant-..."},
        mcp_client=mcp,
        get_tool_definitions=lambda: [
            {"name": "greet", "description": "Greet someone", "input_schema": {
                "type": "object",
                "properties": {"name": {"type": "string"}},
            }},
            *mcp.get_tool_definitions(),
        ],
    )

    # Start streaming (non-blocking, populates event_log)
    asyncio.create_task(runner.run(
        messages=[{"role": "user", "content": "Say hello"}],
        system_prompt="You are a helpful assistant.",
    ))

    # Consume SSE events
    async for entry in event_log.iter_from():
        print(entry.event)
        if entry.event.get("type") == "stream_complete":
            break

    await mcp.shutdown()

asyncio.run(main())

API Reference

AgentRunner

Core streaming agent loop. Sends messages to Claude, processes tool calls, and emits SSE events.

  • Hooks: on_tool_result, on_usage, on_tool_timing — async callbacks for observability
  • Sub-agents: sub_agent_config + spawn_sub_agent() for parallel task delegation
  • Streaming: Emits thinking_delta, text_delta, tool_use, tool_result, stream_complete events

ToolDispatcher

Routes tool calls to local handlers or MCP servers. Supports approval gates for sensitive operations.

  • local_tool_handlers: Dict[str, handler] — local async functions
  • needs_approval / request_approval: Optional approval flow for gated tools
  • approved_tool_types: Session-persistent set of pre-approved tools

McpClientManager

Manages MCP server connections via stdio. Reads server configs from ~/.claude.json.

  • allowed_servers: Whitelist of server names to connect
  • builtin_tool_names: Tool names to skip (avoids collisions with local tools)
  • timeout_overrides: Per-server call timeouts

EventLog

Async event stream for SSE. Append events, iterate from any sequence number.

  • append(event) — add an event
  • iter_from(after_seq) — async iterator, blocks until new events arrive
  • close() — emit terminal event and seal the log

Supporting Types

  • ToolResult = Tuple[Optional[Any], Optional[Dict[str, Any]]](result, error) pair
  • ApprovalRequest / ApprovalDecision — approval flow dataclasses
  • SubAgentConfig — excluded tools, system prompt, max turns for sub-agents
  • ToolResultContext — full context passed to on_tool_result hook
  • LogEntry — sequence number, timestamp, event dict

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ai_agent_gateway-0.1.2.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ai_agent_gateway-0.1.2-py3-none-any.whl (18.1 kB view details)

Uploaded Python 3

File details

Details for the file ai_agent_gateway-0.1.2.tar.gz.

File metadata

  • Download URL: ai_agent_gateway-0.1.2.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for ai_agent_gateway-0.1.2.tar.gz
Algorithm Hash digest
SHA256 09a62a2c82fc9bf7eec12cf65bb2b2a5f9dcf8562c05964e87458ade6f1c8bbc
MD5 cb09363ca18fe970df9ce78a9fd36932
BLAKE2b-256 4f506b2adf2e008781ed2a7fd572d476d206e0fd4fcbab69549fc0a5e4393740

See more details on using hashes here.

File details

Details for the file ai_agent_gateway-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for ai_agent_gateway-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 a42c20afd8c3889cf5d5809f4842a399ed1af25b818592c08eb7c949b51b1b6b
MD5 50b9a3c0efc658b482f9d4ed3bd929af
BLAKE2b-256 45660bdc7ffe24166890c553ed05007df5d8f7b1cd70d5882fd0dc147350b126

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page