> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentsentinel.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Integration

> Use the Model Context Protocol to give LLMs direct access to Agent Sentinel platform features.

## What is MCP?

The **Model Context Protocol (MCP)** provides a standardized way for LLMs to interact with external systems. Agent Sentinel's MCP integration gives LLMs direct, structured access to:

* Platform data (runs, approvals, stats, policies)
* Tool execution (create policies, approve actions, get metrics)
* Prompt templates (common workflows pre-configured)

This enables LLMs to become **autonomous operators** of the Agent Sentinel platform.

<Note>
  `MCPClient` is **fully async**. Every method below is a coroutine and must be `await`ed inside an `async` function or via `asyncio.run(...)`. The examples on this page wrap calls in an `async def main()` block accordingly.
</Note>

## Quick start

```python theme={null}
import asyncio
from agent_sentinel import MCPClient

async def main():
    client = MCPClient(
        platform_url="https://platform.agentsentinel.dev",
        api_token="as_your_api_key_here",
    )

    # Discover available tools
    tools = await client.list_tools()
    print(f"Available tools: {[t.name for t in tools]}")

    # Execute a tool
    result = await client.call_tool(
        tool_name="create_policy",
        arguments={
            "name": "Budget Control",
            "session_budget": 10.0,
            "run_budget": 1.0,
        },
    )
    print(result)

asyncio.run(main())
```

`MCPClient` also supports the async context-manager protocol so the underlying `httpx.AsyncClient` is closed cleanly:

```python theme={null}
async with MCPClient(platform_url=..., api_token=...) as client:
    tools = await client.list_tools()
```

## MCP tools

Tools allow LLMs to perform actions on the platform:

### Available tools

| Tool                    | Description                                |
| ----------------------- | ------------------------------------------ |
| `create_policy`         | Create a new policy with budgets and rules |
| `list_runs`             | Get list of agent runs with filters        |
| `get_pending_approvals` | Fetch pending approval requests            |
| `approve_action`        | Approve a pending action                   |
| `reject_action`         | Reject a pending action                    |
| `get_agent_stats`       | Get statistics for a specific agent        |
| `export_ledger`         | Export activity ledger in various formats  |

### Example: Create a policy

```python theme={null}
async def create():
    result = await client.call_tool(
        tool_name="create_policy",
        arguments={
            "name": "Production Safety",
            "description": "Strict limits for production agents",
            "enabled": True,
            "session_budget": 50.0,
            "run_budget": 5.0,
            "denied_actions": ["delete_database", "drop_table"],
            "rate_limits": {
                "api_call": {"max_count": 100, "window_seconds": 60},
            },
        },
    )
```

### Example: Approve an action

```python theme={null}
async def approve_first_pending():
    approvals = await client.call_tool("get_pending_approvals", {})
    if approvals.get("data"):
        approval_id = approvals["data"][0]["id"]
        await client.call_tool(
            tool_name="approve_action",
            arguments={
                "approval_id": approval_id,
                "approver_email": "manager@company.com",
                "notes": "Approved - verified with customer",
            },
        )
```

## MCP resources

Resources provide read-only access to platform data:

### Available resources

| Resource URI                         | Description                |
| ------------------------------------ | -------------------------- |
| `agentsentinel://runs/latest`        | Get the most recent run    |
| `agentsentinel://approvals/pending`  | List all pending approvals |
| `agentsentinel://stats/dashboard`    | Get dashboard statistics   |
| `agentsentinel://policies/active`    | List all active policies   |
| `agentsentinel://compliance/summary` | Get compliance summary     |

### Example: Access resources

```python theme={null}
async def fetch():
    latest_run = await client.get_resource("agentsentinel://runs/latest")
    print(f"Latest run: {latest_run['data']['run_id']}")

    stats = await client.get_resource("agentsentinel://stats/dashboard")
    print(f"Total cost: ${stats['data']['total_cost']}")

    pending = await client.get_resource("agentsentinel://approvals/pending")
    print(f"Pending approvals: {len(pending['data'])}")
```

## MCP prompts

Prompts are pre-configured workflows that LLMs can execute:

### Available prompts

| Prompt                     | Description                               |
| -------------------------- | ----------------------------------------- |
| `create_budget_policy`     | Guided workflow to create a budget policy |
| `analyze_agent_costs`      | Analyze cost patterns for an agent        |
| `review_pending_approvals` | Review and triage pending approvals       |
| `compliance_audit_report`  | Generate a compliance audit report        |

### Example: Execute a prompt

```python theme={null}
async def analyse():
    result = await client.execute_prompt(
        prompt_name="analyze_agent_costs",
        arguments={"agent_id": "trading-bot", "days": 7},
    )
    print(result["data"]["analysis"])
```

## Convenience methods

The MCP client provides convenience wrappers for common operations (also async):

```python theme={null}
async def manage():
    # Create a policy
    policy = await client.create_policy(
        name="Dev Environment",
        session_budget=1.0,
        enabled=True,
    )

    # List runs with filters
    runs = await client.list_runs(status="failed", min_cost=0.50, limit=10)

    # Get pending approvals
    approvals = await client.get_pending_approvals()

    # Approve / reject
    await client.approve_action(
        approval_id="approval-123",
        approver_email="you@company.com",
        notes="LGTM",
    )
    await client.reject_action(
        approval_id="approval-456",
        approver_email="you@company.com",
        notes="Too risky",
    )

    # Get agent statistics
    stats = await client.get_agent_stats(agent_id="my-agent")
    print(f"Total runs: {stats['total_runs']}")
```

## Using MCP with LLMs

The primary use case is giving LLMs tool-calling access to the platform:

```python theme={null}
import asyncio
from anthropic import Anthropic
from agent_sentinel import MCPClient

async def main():
    mcp = MCPClient(
        platform_url="https://platform.agentsentinel.dev",
        api_token="as_your_api_key_here",
    )
    anthropic = Anthropic()

    tools = await mcp.list_tools()
    anthropic_tools = [
        {
            "name": tool.name,
            "description": tool.description,
            "input_schema": tool.input_schema,
        }
        for tool in tools
    ]

    response = anthropic.messages.create(
        model="claude-opus-4-7",
        max_tokens=4096,
        tools=anthropic_tools,
        messages=[{
            "role": "user",
            "content": "List any pending approvals waiting more than 1 hour at critical priority and summarise them.",
        }],
    )

    if response.stop_reason == "tool_use":
        for block in response.content:
            if block.type == "tool_use":
                result = await mcp.call_tool(
                    tool_name=block.name,
                    arguments=block.input,
                )
                print(result)

asyncio.run(main())
```

## Caching

Tool / resource / prompt lists are cached in-process for performance. Pass `use_cache=False` to force a refresh on a single call:

```python theme={null}
tools = await client.list_tools(use_cache=False)
```

## Global client

Set a default MCP client for your application:

```python theme={null}
from agent_sentinel.mcp import set_default_client, get_default_client

set_default_client(MCPClient(
    platform_url="https://platform.agentsentinel.dev",
    api_token="as_your_api_key_here",
))

# Use anywhere in your app
client = get_default_client()
tools = await client.list_tools()
```

`set_default_client` and `get_default_client` are sync helpers — only the network methods on the client itself are async.

<Note>
  The MCP module requires `httpx` (installed automatically with `pip install agentsentinel-sdk`). If `httpx` is unavailable, `set_default_client`/`get_default_client` are not exported from `agent_sentinel` at the top level — import them directly from `agent_sentinel.mcp` as shown above.
</Note>

## Best practices

<Tip>
  **Use MCP for autonomous operations**: Let LLMs manage policies, approve actions, and analyze costs without manual intervention.
</Tip>

<Tip>
  **Combine with function calling**: Use Claude 4.x or GPT-4 with function calling to enable fully autonomous platform management.
</Tip>

<Warning>
  **Secure your API tokens**: MCP gives LLMs full access to your platform. Use read-only tokens for analysis tasks, and carefully control write access.
</Warning>

## See also

* [Approvals](/sdk/python/approvals) - Human-in-the-loop workflow
* [Policies](/sdk/python/policies) - Policy configuration
* [Platform API Overview](/platform/overview) - Platform API entry point
