Skip to main content

erato-mcp

Track MCP tool calls with analytics that capture what your AI agent was trying to accomplish. The SDK automatically adds a __context parameter where the model writes its intent ("searching for recent orders to answer the user's refund question"), then batches events to Erato Expert Web.

GitHub: erato-hr/erato-mcp-python
PyPI: pip install erato-mcp
Python: >=3.11

Install

pip install erato-mcp

# Optional framework adapters
pip install 'erato-mcp[fastmcp]'
pip install 'erato-mcp[langchain]'

Quickstart (FastMCP)

from fastmcp import FastMCP
from erato_mcp import init
from erato_mcp.integrations.fastmcp import EratoAnalyticsMiddleware

# Initialize with DSN from environment variable ERATO_MCP_DSN
init()

mcp = FastMCP("Demo Server")
mcp.add_middleware(EratoAnalyticsMiddleware())

@mcp.tool()
def search(query: str) -> str:
    """Search the knowledge base."""
    return f"Results for: {query}"

if __name__ == "__main__":
    mcp.run()

The middleware automatically:

  1. Injects a __context parameter into your tool schemas (models fill this with their reasoning)
  2. Strips __context before calling your handler (so you never see it)
  3. Sends analytics events asynchronously in the background

What the model sees:

{
  "name": "search",
  "parameters": {
    "type": "object",
    "properties": {
      "query": {"type": "string"},
      "__context": {
        "type": "string",
        "description": "Briefly explain why you are calling this tool now..."
      }
    },
    "required": ["query", "__context"]
  }
}

What your handler receives:

def search(query: str) -> str:
    # __context was already extracted and sent to analytics
    # You only see the real tool arguments
    ...

LangChain (client-side)

Use this when you don't control the MCP server code (third-party tools):

from langchain_core.tools import Tool
from erato_mcp import init
from erato_mcp.integrations.langchain import track_tool

init()

original_tool = Tool(name="crm_search", func=lambda q: f"Results: {q}")
tracked_tool = track_tool(original_tool, server_id="external-crm")

When the LangChain client is active (valid DSN), it attaches __erato_analytics=client on the MCP call so a dogfooded FastMCP server skips its own capture — History keeps a single client-sourced event. Without an active client DSN, the marker is omitted and server dogfood still records events.

Configuration

DSN and environment variables

Each Erato tenant has its own Expert Web instance at https://<tenant>.expert.erato.hr. The DSN format is:

https://<public_key>@<tenant>.expert.erato.hr/api/mcp-analytics
  • <tenant> — Your account username on the Erato platform (same as in your EEW URL)
  • <public_key> — Tenant-scoped ingest key from your project's MCP analytics settings in EEW (shown once at creation)

Analytics identity is the ingest key plus server_name / server_id from init() (or env). Legacy DSNs with a trailing project slug are accepted; the slug is ignored.

Production example:

export ERATO_MCP_DSN="https://pk_live_a1b2c3d4e5f6@acme.expert.erato.hr/api/mcp-analytics"
export ERATO_MCP_SERVER_NAME="support-mcp-server"
export ERATO_MCP_ENVIRONMENT="production"
from erato_mcp import init

init()  # Reads from environment

Local development example (http + custom port):

export ERATO_MCP_DSN="http://pk_dev_xyz789@acme.lvh.me:3000/api/mcp-analytics"
export ERATO_MCP_ENVIRONMENT="development"
export ERATO_MCP_DEBUG="1"  # Enable verbose logging

Explicit arguments override environment variables:

init(
    dsn="https://pk_live_a1b2c3d4e5f6@acme.expert.erato.hr/api/mcp-analytics",
    server_name="support-mcp-server",
    environment="production",
    debug=False,
)

Supported environment variables:

Variable Purpose
ERATO_MCP_DSN Ingest DSN
ERATO_MCP_SERVER_NAME Default server_name / server id
ERATO_MCP_ENVIRONMENT Deployment environment (default production)
ERATO_MCP_DEBUG 1 / true / yes enables verbose logging

Error handling

  • Explicitly passed but invalid DSN: raises EratoDSNError immediately
  • Environment DSN invalid or missing: logs one clear warning/info line and becomes a no-op (safe for dev/test)
  • Transport/ingest errors: swallowed (debug-logged), never fail your tool calls
from erato_mcp import init, EratoDSNError

try:
    init(dsn="invalid-dsn-format")
except EratoDSNError as e:
    print(f"Configuration error: {e}")

Sampling and privacy

init(
    sample_rate=0.1,                # Send 10% of events
    include_arguments=False,        # Arguments OFF by default
    include_result_preview=False,   # Results OFF by default
    before_send=lambda event: None if "secret" in event.tool_name else event,
)

By default, only context (intent), timing, errors, and an arguments digest are sent. Raw arguments and results are never sent unless you explicitly enable them.

Tracking plain functions

Wrap any callable to track it as a tool call:

from erato_mcp import init, wrap_callable, track

init()

@track(name="calculate")
def add(a: int, b: int) -> int:
    return a + b

# Or wrap an existing function
wrapped = wrap_callable(some_function, name="helper")

# Call normally; __context is stripped automatically
result = add(a=1, b=2, __context="adding user's cart total")

Advanced

How it works (wire contract)

Events are batched and posted to the ingest endpoint:

POST <scheme>://<host>/api/mcp-analytics/envelope
Authorization: Bearer <public_key>
Content-Type: application/json

Envelope payload:

{
  "sdk": {"name": "erato-mcp", "version": "0.2.4"},
  "server": {"id": "...", "name": "..."},
  "sent_at": "2026-12-01T17:00:00.123Z",
  "events": [
    {
      "action": "MCP_TOOL_CALL",
      "tool_name": "search",
      "ok": true,
      "duration_ms": 42.5,
      "context": "user asked about recent orders",
      "context_missing": false,
      "@timestamp": "2026-12-01T17:00:00.100Z",
      "event_id": "uuid",
      "server_id": "...",
      "environment": "production",
      "arguments_digest": "sha256-prefix",
      "sdk_name": "erato-mcp",
      "sdk_version": "0.2.4"
    }
  ]
}

Server-side processing:

  • arguments_preview and result_preview are designed to be stripped by the ingest endpoint (privacy by contract)
  • Only arguments_digest (SHA-256 prefix) is retained for deduplication

Manual MCP hooks

If you're not using FastMCP or LangChain, integrate at the tool call boundary:

from erato_mcp import (
    init,
    inject_context_schema,
    extract_context,
    get_injected_context_param,
    tool_call,
)

init(
    dsn="https://pk_abc@acme.expert.erato.hr/api/mcp-analytics",
    server_name="my-mcp",
)

# 1. At tool registration (modify schemas)
tool["inputSchema"] = inject_context_schema(tool["inputSchema"])
param = get_injected_context_param(tool["inputSchema"])  # e.g. "__context"

# 2. At tool call time (extract context, track execution)
context, cleaned_args = extract_context(
    params["arguments"],
    context_param=param,
)

with tool_call(name=params["name"], arguments=cleaned_args, context=context):
    result = await handler(**cleaned_args)

Default intent arg name is __context (avoids colliding with a real context tool parameter). If that name is already in the schema, the SDK injects __context_2, __context_3, and so on, and stamps the chosen name in x-erato-context-param. Events still store the value as context / context_missing. Override with init(context_param="...") if needed.

You can also use:

  • capture_tool_call(...) — one-shot event capture without a context manager
  • configure_scope(...) — set tags that apply to all events in this scope
  • flush(timeout=2.0) — wait for pending events to send
  • shutdown() — stop the background transport thread

Troubleshooting

Enable debug logging first:

export ERATO_MCP_DEBUG=1

or

init(debug=True)

Common errors:

Issue Cause Fix
404 Not Found on ingest Wrong tenant hostname in DSN Verify <tenant>.expert.erato.hr matches your EEW URL
401 Unauthorized Wrong or expired public key Regenerate key in your project's MCP analytics settings
SDK is silent (no logs) Missing or invalid DSN Check ERATO_MCP_DSN format and enable debug mode
EratoDSNError: Invalid DSN Malformed DSN passed to init(dsn=...) Use https://<key>@<tenant>.expert.erato.hr/api/mcp-analytics

SDK seems inactive (no events sent):

  • Verify your DSN format: https://<key>@<tenant>.expert.erato.hr/api/mcp-analytics
  • Check that init() is called before creating tools/middleware
  • Look for "erato_mcp init: DSN parsed successfully" in logs (debug mode)

Tool calls fail or arguments are wrong:

  • The SDK strips __context before calling your handler; your function signature should NOT include it
  • If a tool already has a context parameter, that's fine — the SDK injects __context by default

Events not appearing in Erato Expert Web:

  • Enable debug mode and check for HTTP errors in logs
  • Verify the tenant hostname matches your EEW instance
  • Check sample_rate (default 1.0 sends everything)
  • Ensure before_send callback isn't dropping events

Import errors:

  • ImportError: erato_mcp.integrations.fastmcp requires... → Install the extra: pip install 'erato-mcp[fastmcp]'
  • Same for LangChain: pip install 'erato-mcp[langchain]'

Metadata

Release files for erato-mcp 0.2.5

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

Source distribution (sdist)

Source distribution for erato-mcp 0.2.5
File Size Uploaded Provenance Actions
erato_mcp-0.2.5.tar.gz 27.7 kB With provenance Details for erato_mcp-0.2.5.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for erato-mcp 0.2.5
File Interpreter ABI Platform Actions
erato_mcp-0.2.5-py3-none-any.whl Python 3 none any Details for erato_mcp-0.2.5-py3-none-any.whl

Total release size: 52.4 kB

Release files / erato_mcp-0.2.5.tar.gz

Download URL erato_mcp-0.2.5.tar.gz
Size 27.7 kB
Tags Source
SHA-256 checksum
How to use checksums
9250a3c6659882ba8981184b11bf350fd351c85b0b7031e0cf4f4caee2e89969
BLAKE2b-256 checksum
How to use checksums
88115a4a29c938f94b1b6b9df8a211490acc79acbddf3a73e1c8839466ca7f6a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Release files / erato_mcp-0.2.5-py3-none-any.whl

Download URL erato_mcp-0.2.5-py3-none-any.whl
Size 24.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
228fc718e362b535ab79eddee0c9346d3ab5ea0de2b06397510e22d4b983fe4b
BLAKE2b-256 checksum
How to use checksums
3889fa02094bbc33de2dba83a113ee88ff9a776fd3f38f14ca008f8ef6e6237a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

Security for erato-mcp 0.2.5

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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for erato_mcp-0.2.5.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 2, 2026.

Transparency log

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