Skip to main content

Official Python SDK for GatewayOps MCP Gateway

Project description

GatewayOps Python SDK

Official Python SDK for the GatewayOps MCP Gateway.

Installation

pip install gatewayops

Quick Start

from gatewayops import GatewayOps

# Initialize the client
gw = GatewayOps(api_key="gwo_prd_...")

# Call an MCP tool
result = gw.mcp("filesystem").tools.call("read_file", path="/data.csv")
print(result.content)

# List available tools
tools = gw.mcp("filesystem").tools.list()
for tool in tools:
    print(f"{tool.name}: {tool.description}")

Features

  • MCP Operations: Call tools, read resources, get prompts
  • Tracing: Distributed tracing with trace context
  • Cost Tracking: Monitor usage and costs
  • Type Safety: Full type hints with Pydantic models
  • Error Handling: Detailed exception hierarchy
  • Retry Logic: Built-in retries with exponential backoff

MCP Operations

Tools

# List tools
tools = gw.mcp("filesystem").tools.list()

# Call a tool
result = gw.mcp("filesystem").tools.call(
    "read_file",
    path="/data/input.csv"
)

# Check for errors
if result.is_error:
    print(f"Error: {result.content}")
else:
    print(result.content)

Resources

# List resources
resources = gw.mcp("database").resources.list()

# Read a resource
content = gw.mcp("database").resources.read("db://users/schema")
print(content.text)

Prompts

# List prompts
prompts = gw.mcp("assistant").prompts.list()

# Get a prompt with arguments
messages = gw.mcp("assistant").prompts.get(
    "summarize",
    arguments={"length": "short"}
)

Tracing

Use trace contexts to correlate multiple operations:

with gw.trace("data-pipeline") as trace:
    # All operations in this block share the trace ID
    data = gw.mcp("filesystem").tools.call("read_file", path="/input.csv")
    result = gw.mcp("processor").tools.call("transform", data=data.content)
    gw.mcp("filesystem").tools.call("write_file", path="/output.csv", content=result.content)

    print(f"Trace ID: {trace.trace_id}")

Viewing Traces

# List recent traces
page = gw.traces.list(limit=10)
for trace in page.traces:
    print(f"{trace.id}: {trace.operation} - {trace.status}")

# Get trace details
trace = gw.traces.get("trace-id-here")
for span in trace.spans:
    print(f"  {span.name}: {span.duration_ms}ms")

Cost Tracking

# Get monthly cost summary
summary = gw.costs.summary(period="month")
print(f"Total cost: ${summary.total_cost:.2f}")
print(f"Request count: {summary.request_count}")

# Costs by MCP server
by_server = gw.costs.by_server()
for breakdown in by_server.by_server:
    print(f"{breakdown.value}: ${breakdown.cost:.2f}")

# Costs by team
by_team = gw.costs.by_team()
for breakdown in by_team.by_team:
    print(f"{breakdown.value}: ${breakdown.cost:.2f}")

Error Handling

The SDK provides specific exceptions for different error types:

from gatewayops import (
    GatewayOpsError,
    AuthenticationError,
    RateLimitError,
    NotFoundError,
    ValidationError,
    InjectionDetectedError,
    ToolAccessDeniedError,
)

try:
    result = gw.mcp("filesystem").tools.call("read_file", path="/secret.txt")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ToolAccessDeniedError as e:
    if e.requires_approval:
        print(f"Tool {e.tool_name} requires approval")
    else:
        print(f"Access denied to {e.tool_name}")
except InjectionDetectedError as e:
    print(f"Prompt injection detected: {e.pattern}")
except NotFoundError:
    print("MCP server or tool not found")
except ValidationError as e:
    print(f"Validation error: {e.message}")
except GatewayOpsError as e:
    print(f"Error [{e.code}]: {e.message}")

Configuration

Custom Base URL

gw = GatewayOps(
    api_key="gwo_prd_...",
    base_url="https://gateway.internal.company.com"
)

Timeout

gw = GatewayOps(
    api_key="gwo_prd_...",
    timeout=60.0  # 60 seconds
)

Retries

gw = GatewayOps(
    api_key="gwo_prd_...",
    max_retries=5  # Default is 3
)

Context Manager

Use the client as a context manager for proper cleanup:

with GatewayOps(api_key="gwo_prd_...") as gw:
    result = gw.mcp("filesystem").tools.call("read_file", path="/data.csv")
# HTTP client is automatically closed

Async Support

For async applications, use the async client:

from gatewayops import AsyncGatewayOps

async def main():
    async with AsyncGatewayOps(api_key="gwo_prd_...") as gw:
        result = await gw.mcp("filesystem").tools.call("read_file", path="/data.csv")
        print(result.content)

Type Reference

ToolCallResult

@dataclass
class ToolCallResult:
    content: Any           # Tool output
    is_error: bool         # Whether the call failed
    metadata: dict | None  # Additional metadata
    trace_id: str | None   # Trace ID for this call
    span_id: str | None    # Span ID within the trace
    duration_ms: int | None  # Execution time
    cost: float | None     # Cost of this call

Trace

@dataclass
class Trace:
    id: str
    org_id: str
    mcp_server: str
    operation: str
    status: str  # "success", "error"
    start_time: datetime
    end_time: datetime | None
    duration_ms: int | None
    spans: list[Span] | None
    error_message: str | None
    cost: float | None

CostSummary

@dataclass
class CostSummary:
    total_cost: float
    period_start: datetime
    period_end: datetime
    request_count: int
    by_server: list[CostBreakdown] | None
    by_team: list[CostBreakdown] | None
    by_tool: list[CostBreakdown] | None

Environment Variables

The SDK supports configuration via environment variables:

export GATEWAYOPS_API_KEY="gwo_prd_..."
export GATEWAYOPS_BASE_URL="https://api.gatewayops.com"
import os
from gatewayops import GatewayOps

gw = GatewayOps(api_key=os.environ["GATEWAYOPS_API_KEY"])

Requirements

  • Python 3.8+
  • httpx >= 0.25.0
  • pydantic >= 2.0.0
  • tenacity >= 8.0.0

License

MIT License - see LICENSE file for details.

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

gatewayops-0.1.0.tar.gz (8.0 kB view details)

Uploaded Source

Built Distribution

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

gatewayops-0.1.0-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

File details

Details for the file gatewayops-0.1.0.tar.gz.

File metadata

  • Download URL: gatewayops-0.1.0.tar.gz
  • Upload date:
  • Size: 8.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.7

File hashes

Hashes for gatewayops-0.1.0.tar.gz
Algorithm Hash digest
SHA256 9bc4c8f7e018ca33c11568226b9cca789ea9b4da7199393f4be68e067104fd63
MD5 b8f06ccc9eb7d863247f1ef8c3c916a8
BLAKE2b-256 43d16ad5ae227e013b1512ef6d639b5f8f9caf55407f691197c63b86a9b36812

See more details on using hashes here.

File details

Details for the file gatewayops-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: gatewayops-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 10.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.7

File hashes

Hashes for gatewayops-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fdf41256275e0bef0d1b71cba147601c4fd69e1b4587a1c77975e5c5e8c2ebfc
MD5 140dce621a4e7411033a60c2722228f8
BLAKE2b-256 272d343800507ca2eb61e0e6a5f00233ba0c0bd01450ecb39a46320d36be743a

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