# Last9 MCP for AI agents

> Connect an AI agent or service to Last9 MCP with bearer authentication and Python examples.

Source: https://last9.io/docs/ai/mcp-for-agents/

Use Last9's MCP server to query telemetry from a Python AI agent, such as an incident bot or on-call assistant. For chat in Last9, use [AI Assistant](/docs/ai/ai-assistant/). For instructions your coding agent can follow, see [agent skills](/docs/ai/agent-skills/), or see [Build your own AI SRE](/docs/ai/build-your-own-ai-sre/) to connect your own bot or investigation service.

Use an MCP client token for programmatic access from agents and services. For IDE setup with browser sign-in, see [Last9 MCP](/docs/ai/mcp/) and the [MCP](https://app.last9.io/mcp) page in Last9.

## Authentication

Two modes are available:

| Mode               | Best for                       | How it works                                                                      |
| ------------------ | ------------------------------ | --------------------------------------------------------------------------------- |
| Hosted MCP + OAuth | Developers in IDEs             | Sign in with a Last9 account through the browser                                  |
| MCP token (Bearer) | Agents, services, CI pipelines | Generate a client token; pass as `Authorization: Bearer <token>` in every request |

### Get an MCP token

1. Open **Query Tokens** in your Last9 organization.
2. Click **New Token** → Token Type: **Client** → Client Type: **MCP**
3. Copy the token and store it in your secrets manager.

The MCP server URL is:

```
https://app.last9.io/api/v4/organizations/<org_slug>/mcp
```

Find your organization slug in your Last9 dashboard URL: `app.last9.io/v2/organizations/<org_slug>/...`.

## Team token management

:::note
Use OAuth for interactive IDE sessions and MCP client tokens for services such as agents, bots, and pipelines.
:::

| Scenario                                | Recommendation                                                                 |
| --------------------------------------- | ------------------------------------------------------------------------------ |
| Developer IDEs                          | Use individual OAuth sign-in.                                                  |
| Shared SRE bot / on-call assistant      | Keep a separate token for the bot in your secrets manager.                     |
| CI pipelines or automation scripts      | Keep a separate token for each pipeline so it can be rotated independently.    |
| Multiple team members sharing one token | Use separate credentials to avoid disrupting everyone when a token is rotated. |

Review token access when ownership of a service changes. Rotate a token if someone who had access to it leaves the team.

:::note
Authentication determines access to Last9. Your AI client or agent determines which MCP calls need confirmation, so configure its tool permissions before allowing dashboard changes or other write actions.
:::

For questions about rate limits or high-volume agent workloads, contact [support@last9.io](mailto:support@last9.io).

## Python agent examples

### Anthropic SDK (Claude)

Install `anthropic` and set `ANTHROPIC_API_KEY`, `ANTHROPIC_MODEL`, `LAST9_ORG_SLUG`, and `LAST9_MCP_TOKEN`. Choose a Claude model that supports the [MCP connector](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector). The example enables two read tools using the current connector beta:

```python
import os
import anthropic

client = anthropic.Anthropic()

response = client.beta.messages.create(
    model=os.environ["ANTHROPIC_MODEL"],
    max_tokens=4096,
    system="You are an SRE assistant. Investigate issues using Last9 observability data.",
    messages=[
        {
            "role": "user",
            "content": "Inspect payment-service errors in production over the last 15 minutes. Report evidence and missing information.",
        }
    ],
    mcp_servers=[
        {
            "type": "url",
            "url": f"https://app.last9.io/api/v4/organizations/{os.environ['LAST9_ORG_SLUG']}/mcp",
            "name": "last9",
            "authorization_token": os.environ["LAST9_MCP_TOKEN"],
        }
    ],
    tools=[{
        "type": "mcp_toolset",
        "mcp_server_name": "last9",
        "default_config": {"enabled": False},
        "configs": {
            "get_service_profile": {"enabled": True},
            "get_service_logs": {"enabled": True},
        },
    }],
    betas=["mcp-client-2025-11-20"],
)

print("\n".join(block.text for block in response.content if block.type == "text"))
```

Expand the tool allowlist to match your investigation. Handle tool failures and incomplete responses before publishing a report.

### LangChain / LangGraph

LangChain provides MCP support through `langchain.mcp` in `langchain[mcp]>=1.4.0`. The API is in beta. See its [MCP migration guide](https://docs.langchain.com/oss/python/migrate/langchain-mcp-adapters) if you use the older `langchain-mcp-adapters` package.

```python
import asyncio
import os
from fastmcp import Client
from langchain.mcp import MCPAdapter
from langchain.agents import create_agent

async def run_sre_agent(question: str) -> str:
    url = f"https://app.last9.io/api/v4/organizations/{os.environ['LAST9_ORG_SLUG']}/mcp"
    client = Client(url, auth=os.environ["LAST9_MCP_TOKEN"])
    async with MCPAdapter(client) as adapter:
        available_tools = await adapter.list_tools()
        allowed_names = {"get_service_profile", "get_service_logs"}
        tools = [tool for tool in available_tools if tool.name in allowed_names]
        agent = create_agent(os.environ["LANGCHAIN_MODEL"], tools)
        result = await agent.ainvoke(
            {"messages": [{"role": "user", "content": question}]}
        )
        return result["messages"][-1].content

if __name__ == "__main__":
    answer = asyncio.run(
        run_sre_agent("Inspect payment-service errors in production over the last 15 minutes. Report evidence and missing information.")
    )
    print(answer)
```

Install the required packages:

```bash
pip install "langchain[mcp,anthropic]>=1.4.0"
```

Set `LANGCHAIN_MODEL` to an `anthropic:<model-id>` supported by your account, and set `ANTHROPIC_API_KEY`, `LAST9_ORG_SLUG`, and `LAST9_MCP_TOKEN`.

### OpenAI Responses API

See [Last9 MCP → Using with OpenAI's Responses API](/docs/ai/mcp/#using-last9-mcp-with-openais-responses-api) for the OpenAI example with Bearer token auth.

## Building an on-call bot

Call an agent from your alert or chat handler with the original question, service, environment, and absolute incident window. Keep each incident's context separate, set a time and tool-call budget, and return incomplete status when required data is missing.

Before sending a report, check tool errors and separate confirmed findings from possible causes. Keep remediation behind your normal review process. Refer to [Build your own AI SRE](/docs/ai/build-your-own-ai-sre/) for the complete design and validation steps.

## Key tools for agent workflows

The MCP server exposes all Last9 observability tools. The most useful for agent workflows:

| Tool                              | What it returns                                                    |
| --------------------------------- | ------------------------------------------------------------------ |
| `get_service_performance_details` | Latency p95, error rate, throughput for a service                  |
| `get_exceptions`                  | Aggregated evidence of server-side exceptions                      |
| `get_service_dependency_graph`    | Dependency throughput, response-time, and error metrics            |
| `get_apm_service_deviations`      | Regressions/improvements vs an equal-duration baseline window      |
| `get_trace_waterfall`             | Bounded parent/child waterfall for one trace with timing/self-time |
| `get_trace_attribute_deviations`  | Attribute values that differ between slow/fast or error cohorts    |
| `get_alerts`                      | Currently firing alert rules and severity                          |
| `get_logs`                        | LogJSON pipeline results, including filtered logs and aggregates   |
| `get_service_logs`                | Raw service log lines with severity and body filters               |
| `get_service_profile`             | Available telemetry signals and context for a service              |
| `get_change_events`               | Recent deployments and config changes (correlate with incidents)   |
| `prometheus_range_query`          | Run any PromQL expression over your metrics                        |
| `did_you_mean`                    | Fuzzy-match entity names to avoid empty results from typos         |

For the full reference, see [Available Tools](/docs/ai/mcp/#available-tools) on the main MCP page.

---

## Troubleshooting

- **`401 Unauthorized`**

  Check that:

  - The `Authorization` header is `Bearer <token>` (not `Basic`, not the token alone)
  - The token is an **MCP-type** Client token from Query Tokens.

- **Tools return empty results**

  Time-window defaults vary by tool. For example, `get_logs` defaults to 5 minutes, while an exact trace lookup defaults to 4320 minutes. Pass an explicit window when investigating an incident:

  ```python
  # In tool parameters passed by the agent
  {"lookback_minutes": 360}
  ```

  If the service name returns no results, have the agent call `did_you_mean` first to resolve the correct name.

- **Rate limit errors**

  Each organization has rate limits for its endpoints. Limit concurrent requests across all agent instances using the organization. For workloads with many requests, contact [support@last9.io](mailto:support@last9.io) to discuss limits.

Please get in touch with us on [Discord](https://discord.com/invite/Q3p2EEucx9) or [Email](mailto:support@last9.io) if you have any questions.
