Skip to main content

gopher-mcp-python Python SDK

Python SDK for gopher-mcp-python, providing AI agent orchestration with native C++ performance through ctypes FFI bindings.

Features

  • Python 3.8+ compatibility
  • pip/setuptools build system
  • ctypes FFI bindings to native library
  • GopherAgent class with builder pattern configuration
  • Context manager support for automatic resource cleanup
  • Typed errors (AgentError, ApiKeyError, ConnectionError, TimeoutError)
  • Comprehensive test suite with pytest

Requirements

  • Python 3.8 or higher
  • venv and pip for PyPI installation, examples, and development workflows
  • Native gopher-mcp-python library (built from source)
  • On Linux, system OpenSSL runtime libraries (libssl / libcrypto) from your distribution. Native wheels do not bundle OpenSSL, so OS security updates remain effective.

On Debian/Ubuntu, install the Python venv and pip packages before using the PyPI install path, running examples, or setting up development dependencies:

sudo apt-get install python3 python3-venv python3-pip

Installation

From Source

  1. Clone the repository:
git clone https://github.com/GopherSecurity/gopher-mcp-python.git
cd gopher-mcp-python
  1. Build the native library:
./build.sh
  1. Install the Python package:
python3 -m pip install -e .

Quick Start

Using API Key

from gopher_mcp_python import GopherAgent, GopherAgentConfig

# Create configuration with API key
config = (GopherAgentConfig.builder()
    .provider("AnthropicProvider")
    .model("claude-3-haiku-20240307")
    .api_key("your-api-key")
    .build())

# Create and use agent with context manager
with GopherAgent.create(config) as agent:
    response = agent.run("What time is it in Tokyo?")
    print(response)

Using JSON Server Configuration

from gopher_mcp_python import GopherAgent, GopherAgentConfig

# Create configuration with server config
config = (GopherAgentConfig.builder()
    .provider("AnthropicProvider")
    .model("claude-3-haiku-20240307")
    .server_config('{"mcpServers": [...]}')
    .build())

# Create agent
agent = GopherAgent.create(config)
try:
    response = agent.run("What is the weather?")
    print(response)
finally:
    agent.dispose()

Using Convenience Methods

from gopher_mcp_python import GopherAgent

# Create with API key (shorthand)
agent = GopherAgent.create_with_api_key(
    provider="AnthropicProvider",
    model="claude-3-haiku-20240307",
    api_key="your-api-key"
)

# Or with server config
agent = GopherAgent.create_with_server_config(
    provider="AnthropicProvider",
    model="claude-3-haiku-20240307",
    server_config='{"mcpServers": [...]}'
)

Getting Detailed Results

from gopher_mcp_python import GopherAgent

with GopherAgent.create(config) as agent:
    result = agent.run_detailed("What time is it?")

    if result.is_success():
        print(f"Response: {result.response}")
        print(f"Iterations: {result.iteration_count}")
        print(f"Tokens used: {result.tokens_used}")
    elif result.is_timeout():
        print(f"Request timed out: {result.error_message}")
    else:
        print(f"Error: {result.error_message}")

API Reference

GopherAgent

Main class for interacting with the gopher-mcp-python native library.

Static Methods

  • GopherAgent.init() - Initialize the library (called automatically)
  • GopherAgent.shutdown() - Shutdown the library
  • GopherAgent.is_initialized() - Check if library is initialized
  • GopherAgent.create(config) - Create an agent with configuration
  • GopherAgent.create_with_api_key(provider, model, api_key) - Convenience method
  • GopherAgent.create_with_server_config(provider, model, server_config) - Convenience method

Instance Methods

  • agent.run(query, timeout_ms=60000) - Run a query and get response string
  • agent.run_detailed(query, timeout_ms=60000) - Run a query and get AgentResult
  • agent.dispose() - Release resources
  • agent.is_disposed() - Check if agent is disposed

GopherAgentConfig

Configuration class with builder pattern.

config = (GopherAgentConfig.builder()
    .provider("AnthropicProvider")  # Required
    .model("claude-3-haiku-20240307")  # Required
    .api_key("key")  # Either api_key or server_config required
    .server_config("{...}")  # Either api_key or server_config required
    .build())

AgentResult

Result class with status and metadata.

  • result.response - Response text
  • result.status - AgentResultStatus enum
  • result.iteration_count - Number of iterations
  • result.tokens_used - Tokens consumed
  • result.error_message - Error message (if applicable)
  • result.is_success() - Check if successful
  • result.is_error() - Check if error
  • result.is_timeout() - Check if timeout

Provider OAuth Elicitation

Provider OAuth requested during a tool call is handled automatically by default. For URL-mode elicitation, the SDK opens the authorization URL when possible, prints it as a fallback, waits for the user to finish the browser flow, and then lets the native agent retry the tool call.

No example-level elicitation configuration is required:

agent = GopherAgent.create_with_url(provider, model, mcp_url)

Use GopherAgentCreateOptions only when you need a custom synchronous handler or want to disable browser opening while still printing the URL:

from gopher_mcp_python import GopherAgentCreateOptions

agent = GopherAgent.create_with_url(
    provider,
    model,
    mcp_url,
    GopherAgentCreateOptions(
        elicitation={
            "open_browser": False,
            "handler": lambda request: "accept",
        },
    ),
)

First-step MCP server OAuth is controlled separately by the oauth create option. Setting oauth={"mode": "disabled"} skips SDK OAuth discovery for the MCP endpoint but still leaves provider elicitation enabled.

Exceptions

  • AgentError - Base exception for agent errors
  • ApiKeyError - Invalid API key
  • ConnectionError - Connection failed
  • TimeoutError - Operation timed out

Development

Running Tests

pytest

For deterministic OAuth auto verification with a local custom IdP and local MCP server/gateway endpoints, see docs/oauth-auto-custom-idp.md.

Code Formatting

This project uses Black for code formatting and Ruff for linting.

Format code:

black .

Check formatting without modifying:

black --check .

Run linter:

ruff check .

Fix linting issues:

ruff check --fix .

Building the Native Library

./build.sh

Clean Build

./build.sh --clean

Environment Variables

  • GOPHER_MCP_PYTHON_LIBRARY_PATH - Custom path to native library
  • DEBUG - Enable debug output for library loading

License

See LICENSE file for details.

Metadata

Release files for gopher-mcp-python 0.1.39

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gopher-mcp-python 0.1.39
File Size Uploaded Provenance
gopher_mcp_python-0.1.39.tar.gz 93.3 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for gopher-mcp-python 0.1.39
File Interpreter ABI Platform
gopher_mcp_python-0.1.39-py3-none-any.whl Python 3 none any Details

Total release size: 168.8 kB

Release files / gopher_mcp_python-0.1.39.tar.gz

Download URL gopher_mcp_python-0.1.39.tar.gz
Size 93.3 kB
Tags Source
SHA-256 checksum
How to use checksums
ce5bf11e4ae243ddcdce0ca7eb0b88aa0c277b492b5423a8eb64c749a27ce5cc
BLAKE2b-256 checksum
How to use checksums
0bef587440fd952eb7fcd71a6595612d6dc4847cda89eca2b48d66d527e7b6e3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Release files / gopher_mcp_python-0.1.39-py3-none-any.whl

Download URL gopher_mcp_python-0.1.39-py3-none-any.whl
Size 75.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
070ca0a6c33ce710426b16a029c9057f3520f463aadf0c88869db33fc3512394
BLAKE2b-256 checksum
How to use checksums
b4750bca0aaff1772b5e9f773c67127814f3c00a028aaa874c7f150d581edb16
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.16

Security for gopher-mcp-python 0.1.39

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page