Skip to main content

mcpgateway-sdk

PyPI version Python versions License: MIT

Python SDK for MCP Gateway — the enterprise platform for hosting, managing, and securing MCP (Model Context Protocol) servers.

Installation

pip install mcpgateway-sdk

Quick start

import asyncio
from mcpgateway_sdk import MCPGateway

async def main():
    async with MCPGateway(api_key="sk-...", url="http://localhost:8000") as gw:
        # Semantic search for tools across all servers
        tools = await gw.tools.search("get current weather")
        print(tools[0].tool_name, tools[0].score)

        # Execute a tool
        result = await gw.tools.execute(
            "get_weather", {"city": "NYC"}, server_name="weather"
        )
        print(result)

asyncio.run(main())

Features

  • Servers — full CRUD, typed remote registration, readiness, lifecycle, health checks, bulk actions, catalog import, tool sync (with bundle-update control), tool overrides, credentials, OAuth config
  • Tools — semantic search, execute by name, lookup by server/tool name
  • Skills — create, upload, catalog import, package download
  • Script tools — upload a server-owned script-tool package (servers.create_script_tool_package)
  • Sessions — per-session tool scoping for multi-tenant isolation
  • Sandboxes — isolated execution environments with file I/O and code exec
  • Auth — API key management
  • Cache — server-side cache control

All resources are accessed as attributes on the client: gw.servers, gw.tools, gw.skills, gw.sessions, gw.sandboxes, gw.auth, gw.cache, gw.oauth_apps, and gw.oauth_templates.

Configuration

The client reads configuration from explicit parameters or environment variables:

Parameter Environment variable Default
api_key MCPGATEWAY_TOKEN
url MCPGATEWAY_URL http://localhost:8000
timeout 30.0
import os
os.environ["MCPGATEWAY_TOKEN"] = "sk-..."
os.environ["MCPGATEWAY_URL"] = "https://gateway.example.com"

async with MCPGateway() as gw:  # picks up from env
    ...

Usage examples

All examples below assume gw is an active client from async with MCPGateway(...) as gw.

Manage servers

# List all running servers
servers = await gw.servers.list(status="running")

# Import a server from the built-in catalog
server = await gw.servers.import_from_catalog(
    registry="npm",
    registry_id="@anthropic/time-mcp",
    name="time-server",
)

# Start, stop, health check
await gw.servers.start(server.id)
health = await gw.servers.health(server.id)
await gw.servers.stop(server.id)

# Re-sync tools from the source. By default, new/renamed tools are also
# propagated into any bundles that curate this server. Check how many bundles
# would be affected, then opt out of the bundle update if you prefer.
usage = await gw.servers.bundle_usage(server.id)  # {"bundle_count": 3}
await gw.servers.sync_tools(server.id)                       # update bundles (default)
await gw.servers.sync_tools(server.id, update_bundles=False) # leave bundles alone

# Uploading a script-tool package works the same way (default on):
await gw.servers.create_script_tool_package(server.id, "package.zip")
await gw.servers.create_script_tool_package(server.id, "package.zip", update_bundles=False)

Register an authenticated remote MCP server

from mcpgateway_sdk.models import RemoteAuthentication, RemoteServerRegistration, ServerReadiness

# Probe first: only OAuth and no-auth can be safely preselected by the gateway.
probe = await gw.oauth_apps.probe_auth("https://mcp.example.com/mcp")
print(probe.outcome)

server = await gw.servers.register_remote(
    RemoteServerRegistration(
        name="example-remote",
        display_name="Example Remote",
        url="https://mcp.example.com/mcp",
        authentication=RemoteAuthentication(
            type="api_key",
            config={"location": "header", "name": "X-API-Key"},
            secrets={"api_key": "set-once-and-never-read-back"},
        ),
    )
)
if server.readiness is ServerReadiness.AWAITING_CREDENTIALS:
    print("A member still needs to connect their account")
elif server.readiness is ServerReadiness.FAILED:
    print(server.last_error)

The typed remote path supports only none, api_key, bearer, basic, and oauth2. It rejects HMAC and query-parameter API keys locally. servers.create(**fields) remains available for existing generic server workflows.

For OAuth, list a template and create the app before registering the server; the app response's id is the config["app_id"] value for RemoteAuthentication(type="oauth2", ...):

import os

from mcpgateway_sdk.models import OAuthAppCreate

template = (await gw.oauth_templates.list())[0]
app = await gw.oauth_apps.create(
    OAuthAppCreate(
        alias="example-oauth",
        name="Example OAuth",
        template_id=template.id,
        client_id="provider-issued-client-id",
        client_secret=os.environ["OAUTH_CLIENT_SECRET"],
    )
)
print(app.id)  # Pass this UUID as the remote OAuth2 config.app_id.

Search and execute tools

# Semantic search across all servers
results = await gw.tools.search("convert PDF to text", limit=3)
for r in results:
    print(f"{r.server_name}/{r.tool_name} — score: {r.score:.2f}")

# Execute a specific tool
output = await gw.tools.execute(
    "read_pdf",
    {"url": "https://example.com/report.pdf"},
    server_name="document-reader",
)

Work with skills

# Upload a skill from a local file
skill = await gw.skills.upload(file_path="./my_skill.md")

# Browse the skill catalog
entries = await gw.skills.catalog("builtin")

Sessions with scoped tools

# Allow specific tools + wildcard for entire servers
session = await gw.sessions.create(
    allowed_tool_names=["VVMCP__kb_finance", "HOTSPOT__*", "GMAIL__*"],
    denied_tool_names=["HOTSPOT__internal_debug"],
)

# Use the session ID for MCP connections with restricted tool access
print(session.id)

# Update only the deny list (allowed list unchanged)
session = await gw.sessions.update(
    session.id,
    denied_tool_names=["HOTSPOT__internal_debug", "HOTSPOT__admin_reset"],
)

# Refresh session activity
await gw.sessions.touch(session.id)

Sandbox execution

# Create a sandbox
sandbox = await gw.sandboxes.create(image="python:3.12")

# Execute code
result = await gw.sandboxes.exec(sandbox.id, command="python -c 'print(1+1)'")
print(result.stdout)

# Upload / download files
await gw.sandboxes.upload_file(sandbox.id, "data.csv", content=b"a,b\n1,2")
files = await gw.sandboxes.list_files(sandbox.id)

# Clean up
await gw.sandboxes.destroy(sandbox.id)

API key management

# Create a new API key
key = await gw.auth.create_api_key(name="ci-pipeline", expires_in_days=90)
print(key.key)  # Only shown once

# List and rotate keys
keys = await gw.auth.list_api_keys()
rotated = await gw.auth.rotate_api_key(keys[0].id)

SDK cache

# Store a value with TTL (default 300 seconds)
await gw.cache.set("last_run", {"status": "ok"}, ttl=600)

# Retrieve — returns None if key doesn't exist
value = await gw.cache.get("last_run")

Error handling

The SDK raises typed exceptions that map to HTTP status codes:

from mcpgateway_sdk import (
    GatewayError,    # Base — all API errors
    AuthError,       # 401 Unauthorized
    ForbiddenError,  # 403 Forbidden
    NotFoundError,   # 404 Not Found
    ConflictError,   # 409 Conflict
    ValidationError, # 422 Unprocessable Entity
    RateLimitError,  # 429 Too Many Requests
)

try:
    await gw.servers.get("nonexistent-id")
except NotFoundError:
    print("Server not found")
except GatewayError as e:
    print(f"API error [{e.status_code}]: {e.message}")

Version compatibility

The client automatically checks its version against the server on connect (via async with). If there is a major/minor mismatch, it emits a warning:

UserWarning: SDK version 0.16.0 does not match server version 0.17.0.
Update with: pip install --upgrade mcpgateway-sdk

Disable this check with MCPGateway(check_version=False).

MCP connection

Use the client to get connection details for direct MCP protocol access:

async with MCPGateway(api_key="sk-...") as gw:
    print(gw.mcp_url)       # http://localhost:8000/mcp/gateway
    print(gw.auth_headers)   # {"Authorization": "Bearer sk-..."}

Requirements

License

MIT

Download files

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

Source Distribution

mcpgateway_sdk-0.57.0.tar.gz (126.1 kB view details)

Uploaded Source

Built Distribution

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

mcpgateway_sdk-0.57.0-py3-none-any.whl (62.0 kB view details)

Uploaded Python 3

File details

Details for the file mcpgateway_sdk-0.57.0.tar.gz.

File metadata

  • Download URL: mcpgateway_sdk-0.57.0.tar.gz
  • Upload date:
  • Size: 126.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.12.3

File hashes

Hashes for mcpgateway_sdk-0.57.0.tar.gz
Algorithm Hash digest
SHA256 57b19511e9781e6302f4e798448b708b7d4116e95630be00fbc55ef103bc1e43
MD5 8147fd5bf601c60c261036cb732200cb
BLAKE2b-256 859f5189b5aeb996eccf35599dd1bf4d8a547e2140d76c3a3fc02cbe695bd6ec

See more details on using hashes here.

File details

Details for the file mcpgateway_sdk-0.57.0-py3-none-any.whl.

File metadata

File hashes

Hashes for mcpgateway_sdk-0.57.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dc7bcff94f53648c00a1863736a79620fdec6a3bfbdaaa4ac66601977401de3f
MD5 b0d007937f220c1627908377e3302875
BLAKE2b-256 e24581258bc87dc6663a080f4db0d840341588bc8cadbc718d9e7adae5a5ff7b

See more details on using hashes here.

Release history Release notifications | RSS feed

0.59.0

2 files

0.58.0

2 files

This release

0.57.0 This release

2 files

0.56.0

2 files

0.55.0

2 files

0.54.0

2 files

0.53.0

2 files

0.52.0

2 files

0.51.0

2 files

0.50.0

2 files

0.49.0

2 files

0.48.0

2 files

0.47.7

2 files

0.47.6

2 files

0.47.5

2 files

0.47.4

2 files

0.47.3

2 files

0.47.2

2 files

0.47.1

2 files

0.47.0

2 files

0.46.0

2 files

0.45.0

2 files

0.44.1

2 files

0.44.0

2 files

0.43.0

2 files

0.42.0

2 files

0.41.0

2 files

0.40.3

2 files

0.40.2

2 files

0.40.1

2 files

0.40.0

2 files

0.39.2

2 files

0.39.1

2 files

0.39.0

2 files

0.38.1

2 files

0.38.0

2 files

0.37.0

2 files

0.36.0

2 files

0.35.0

2 files

0.34.5

2 files

0.34.4

2 files

0.34.3

2 files

0.34.2

2 files

0.34.1

2 files

0.34.0

2 files

0.33.0

2 files

0.32.1

2 files

0.32.0

2 files

0.31.2

2 files

0.31.1

2 files

0.31.0

2 files

0.30.1

2 files

0.30.0

2 files

0.29.0

2 files

0.28.0

2 files

0.27.1

2 files

0.27.0

2 files

0.26.0

2 files

0.25.2

2 files

0.25.1

2 files

0.25.0

2 files

0.24.0

2 files

0.23.0

2 files

0.22.0

2 files

0.21.0

2 files

0.20.0

2 files

0.19.0

2 files

0.18.2

2 files

0.18.1

2 files

0.18.0

2 files

0.17.1

2 files

0.17.0

2 files

0.1.0

2 files

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