Metadata-Version: 2.4
Name: erato-mcp
Version: 0.2.6
Summary: Erato MCP analytics SDK — Sentry-style tool-call observability with agent intent (context) capture.
Author-email: Erato <dev@erato.hr>
License-Expression: MIT
Project-URL: Homepage, https://github.com/erato-hr/erato-mcp-python
Project-URL: Repository, https://github.com/erato-hr/erato-mcp-python
Project-URL: Issues, https://github.com/erato-hr/erato-mcp-python/issues
Keywords: mcp,analytics,observability,fastmcp,langchain
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Provides-Extra: fastmcp
Requires-Dist: fastmcp>=2.9; extra == "fastmcp"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.3; extra == "langchain"
Provides-Extra: test
Requires-Dist: pytest<9,>=8; extra == "test"
Requires-Dist: pytest-asyncio<1,>=0.24; extra == "test"
Requires-Dist: respx<1,>=0.21; extra == "test"
Provides-Extra: dev
Requires-Dist: erato-mcp[fastmcp,langchain,test]; extra == "dev"
Dynamic: license-file

# 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](https://github.com/erato-hr/erato-mcp-python)  
**PyPI:** `pip install erato-mcp`  
**Python:** `>=3.11`

## Install

```bash
pip install erato-mcp

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

## Quickstart (FastMCP)

```python
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:**

```json
{
  "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:**

```python
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):

```python
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) **and** the MCP `tools/list` schema already includes Erato intent (`__context` from server dogfood), it attaches `__erato_analytics=client` so the server middleware **skips** its own capture. For plain MCP servers (no Erato middleware), the client still injects/strips `__context` for the model but does **not** send the marker — otherwise the tool handler would reject the unexpected argument.

## 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:**

```bash
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"
```

```python
from erato_mcp import init

init()  # Reads from environment
```

**Local development example (http + custom port):**

```bash
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:

```python
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

```python
from erato_mcp import init, EratoDSNError

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

### Sampling and privacy

```python
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:

```python
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:**

```json
{
  "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:

```python
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:**

```bash
export ERATO_MCP_DEBUG=1
```

or

```python
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]'`
