MCP Integration

Connect AI agents and IDEs to Neatlogs via MCP to query traces, inspect and create detections, and work on incident fixes.

The Model Context Protocol (MCP) is a standard that allows AI agents and IDEs to interact with external systems through a unified tool interface. Neatlogs exposes an MCP server that lets coding agents and IDE plugins access observability data, search traces, author detections, and work on the fixes behind incidents directly from an agent workflow.


What You Can Do

With Neatlogs MCP, your agents can:

  • Search production traces - Free-text query with filters for workflow, framework, model, detection, duration, token count, errored spans, and cost
  • Get full trace context - Fetch a trace's spans with inputs, outputs, code locations, detections, and evaluations
  • Read analytics - Pull dashboard KPIs, cost, errors, latency, and tool breakdowns for a time window
  • List detections - See which detections (Hallucination, Jailbreak, Task Failure, …) the project runs
  • Track detection trends - Analyze hourly/daily/weekly occurrence rates
  • Author detections - Dry-run a regex or conditional rule, then create the detection with a 14-day backfill
  • Read fixes - List the fixes behind incidents, with root cause, evidence, and recommended actions
  • Manage fixes - Accept, dismiss, update status, and edit fix fields
  • Review fix history - List, fetch, and restore saved content versions
  • Log agent work - Push traces back to Neatlogs from your agent's execution
  • Investigate - Reload the investigation trail that produced a fix
Note

In the dashboard, fixes appear with their incidents on the Incidents page. The MCP tools that work with them keep legacy names: the triage_ prefix, triage_id parameters, and "fix" in descriptions and errors.


Getting Started

Step 1: Get Your API Key

Each Neatlogs project has its own API key. Open Settings → Project → API keys in the dashboard with the project selected, and copy its key.

Warning

A project API key reads your project's data, and through MCP it can also log traces, create detections, and update fixes. Treat it like a password and never commit it to version control. Store it in environment variables or a secrets manager.

Step 2: Connect Your Agent or IDE

The fastest path is the wizard, which wires the MCP server into Claude Code or Cursor for you:

npx @neatlogs/wizard@latest mcp

It prompts for the project API key. For an EU project, add --region eu.

To connect manually, add a neatlogs entry to your client's MCP config (.mcp.json for Claude Code, .cursor/mcp.json for Cursor):

{
  "mcpServers": {
    "neatlogs": {
      "type": "http",
      "url": "https://ingest.neatlogs.com/mcp",
      "headers": {
        "Authorization": "Bearer YOUR_PROJECT_KEY"
      }
    }
  }
}

The MCP server lives at /mcp on the same host as your SDK endpoint: https://ingest.neatlogs.com/mcp in the US region, https://eu.ingest.neatlogs.com/mcp in the EU region, or your dedicated deployment's ingest host.

Authentication: Include the key in either header:

  • Authorization: Bearer <your-api-key> (preferred — what most MCP clients send)
  • x-api-key: <your-api-key> (legacy, still accepted)

Step 3: Verify and Start Using Tools

Restart your editor and the Neatlogs tools appear in your agent's tool list. Ask the agent to call ping to verify the connection, and whoami to confirm which project the session is bound to. From there it can call any tool — for example, search traces for a specific error.


Connection Methods

Best for: Claude Code, Cursor, agents, IDE plugins

Stateful sessions that you can reuse for multiple requests. The first initialize request creates a session; the server returns its id in the mcp-session-id response header.

POST https://ingest.neatlogs.com/mcp
Authorization: Bearer <your-api-key>
Content-Type: application/json
Accept: application/json, text/event-stream

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": { "name": "my-agent", "version": "1.0" }
  }
}

Then call tools on the session, passing the id back in the mcp-session-id header:

POST https://ingest.neatlogs.com/mcp
Authorization: Bearer <your-api-key>
Content-Type: application/json
Accept: application/json, text/event-stream
mcp-session-id: <session-id-from-initialize>

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "search_traces",
    "arguments": {
      "query": "timeout"
    }
  }
}

Features:

  • Stateful sessions (reuse connections)
  • Include mcp-session-id header to resume
  • GET, POST, DELETE supported
  • POST bodies must be Content-Type: application/json, up to 1 MB
  • Tool calls count toward the project's rate limit
  • Best for agents and IDEs

Best for: Legacy clients that don't speak streamable HTTP

Event-based streaming with persistent connections.

GET https://ingest.neatlogs.com/mcp/sse
Authorization: Bearer <your-api-key>

# Connection opens, receives events
# Then POST messages to:
POST https://ingest.neatlogs.com/mcp/messages?sessionId=<session-id>

Features:

  • Server-sent events (SSE)
  • Keep connection alive for streaming
  • The GET stream is not rate-limited (won't break long-lived connections); tool calls posted to /mcp/messages are

Authentication Patterns

Bearer Token (Standard)

Authorization: Bearer <your-project-api-key>

Preferred by MCP clients. Works with any integration.

Legacy Header (x-api-key)

x-api-key: <your-project-api-key>

Older integrations. Still supported for backward compatibility.

Scope

API keys are unique per project. Each key grants access to one project only - the session sees only that project's traces, detections, and fixes.

Service accounts

An organization service-account token (nlsa_ prefix) can also open a session. Send the target project in an x-project-id header. These sessions expose only read tools, each checked against the account's permissions and scopes. See the MCP Tools Reference.


Session Management

Creating a Session

The initialize request creates a new session:

POST https://ingest.neatlogs.com/mcp
Authorization: Bearer <your-api-key>

The server returns the session id in the mcp-session-id response header. Store this for subsequent calls.

Resuming a Session

Reuse an existing session by including the header:

POST https://ingest.neatlogs.com/mcp
Authorization: Bearer <your-api-key>
mcp-session-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Same session, same tools advertised, same context. Sessions are bound to the project and key that created them - reusing a session id with a different key returns 403.

Cleaning Up

Send DELETE to tear down a session:

DELETE https://ingest.neatlogs.com/mcp
Authorization: Bearer <your-api-key>
mcp-session-id: a1b2c3d4-e5f6-7890-abcd-ef1234567890

Sessions also close when the underlying connection closes or after 10 minutes without requests. If a session id stops resolving (404 Session not found), initialize a new one.

Capacity

Neatlogs caps concurrent sessions at 128 per project and 256 per organization. Beyond that, new sessions get 429 with a Retry-After header. Reuse sessions instead of opening one per request.


Rate Limiting

  • Limit: 60 tool calls per 60 seconds per project by default
  • Shared by: every session and key for the project
  • Counts: tools/call requests, except ping
  • Doesn't count: initialize, tools/list, session teardown, and GET/SSE streams
  • Response: 429 with code MCP_TOOL_CALL_RATE_LIMITED, retryAfterSeconds, and a Retry-After header. Responses also carry RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset headers.

Retry after the indicated delay, with backoff. Each tool call has a 15-second time limit.


Tool Overview

The default project-key catalog includes the 26 tools below. Deployments and authentication scope can change which tools are available; use the authenticated session's tools/list as the source of truth.

ToolPurposeUse Case
pingHealth checkVerify connection
whoamiGet project IDConfirm authentication
search_tracesKeyword or semantic searchFind errors, slow or expensive traces
get_trace_contextFetch a trace's spans and metricsView execution details
get_trace_evaluationsRead evaluation answers and judge runsCheck how a run was scored
log_tracePush tracesAgent reports its work
get_project_analyticsDashboard aggregatesKPIs, cost, errors for a window
list_detectionsList detectionsSee what's being monitored
get_detection_trendTrend analysisTrack detection frequency
get_detection_statusDetection stateCheck activation and backfill
get_detection_capabilitiesDetection engines and schemasPlan a new detection
list_detection_groupsList detection groupsPick a group_id
create_detection_groupCreate a groupWhen no group fits
preview_detectionDry-run a ruleCheck matches before creating
create_detectionCreate a detectionStart monitoring with a 14-day backfill
triage_listList fixesSee open work
triage_getFix detailsReview root cause + action
triage_get_investigationInvestigation contextRead investigation thread
triage_list_stepsInvestigation stepsSee agent's analysis steps
triage_list_versionsList fix versionsBrowse saved content versions
triage_get_versionFetch fix versionRead one version snapshot by number
triage_restore_versionRestore fix versionRoll content back to an older version
triage_acceptAccept fixMove a draft onto the board
triage_dismissDismiss fixArchive a false positive
triage_update_statusChange statusMove across in_progress / resolved / archived
triage_updateEdit fix fieldsUpdate title, severity, label, content

See the MCP Tools Reference for detailed schemas and examples.


Common Workflows

Workflow 1: Agent Debugging Its Own Output

1. Agent completes a task
2. Calls log_trace() to push execution trace
3. Calls search_traces(query: "timeout", min_duration: 5000) to find similar slow traces
4. Calls get_trace_context(trace_id) to compare
5. Uses context to improve next attempt

Workflow 2: IDE Plugin Finding Root Causes

1. Developer sees error in IDE
2. Plugin calls search_traces(query: error_message)
3. Fetches matching production traces
4. Shows top detections via list_detections()
5. Links to the matching incident in Neatlogs

Workflow 3: Agent Working on a Fix

1. Agent calls triage_list(status: "draft") and finds five drafts
2. Calls triage_get(triage_id) to review root cause
3. Asks the user for their team email, then calls triage_accept(triage_id, user_email)
4. Calls triage_update_status(triage_id, user_email, "in_progress") and implements the change
5. After deployment, calls triage_update_status(triage_id, user_email, "resolved", resolution_note)

Workflow 4: Monitoring Regressions

1. Agent calls list_detections()
2. Picks a detection to watch, e.g. "Hallucination"
3. Calls get_detection_trend(detection_name: "hallucination", period: "7d", granularity: "day")
4. If trending up, digs into matching traces via search_traces(detection_name: "hallucination")

Workflow 5: Creating a Detection

1. Agent calls list_detection_groups() and picks a group_id (or create_detection_group)
2. Calls preview_detection(type: "regex", config: { output_pattern: "payment failed" })
3. If total_count > 0, calls create_detection(display_name, group_id, type, config)
4. Calls get_detection_status(detection_id) to follow the 14-day backfill

Error Handling

Authentication Errors

StatusReasonFix
401Missing API keyInclude the Authorization header
401Invalid API keyCheck the key against Settings → Project → API keys
403Session belongs to a different project or keyUse the key that created the session, or initialize a new one

Validation Errors

StatusReasonFix
400Missing mcp-session-id on DELETEInclude the session header
404Unknown session idInitialize a new session
415POST without Content-Type: application/jsonSend JSON with that content type

Server Errors

StatusReasonFix
429Tool-call rate limit or session capacity exceededWait for Retry-After, then retry
503Server draining or capacity temporarily unavailableRetry after Retry-After
500Internal server errorRetry with backoff; contact support if persistent

Transport errors return JSON with an error field. A tool that fails returns a normal result with isError: true and an errorCode such as invalid_argument, not_found, or not_enabled; see Errors. Calling a tool that isn't enabled returns a JSON-RPC error - disabled tools are never advertised in tools/list, so a well-behaved client won't hit this.


Best Practices

Note

Do's:

  • Store API keys securely (env vars, secrets manager)
  • Reuse sessions when making multiple calls
  • Verify the connection with ping / whoami before relying on it
  • Set reasonable client timeouts (15-30 seconds)
  • Ask the user before calling write tools, which record their email as the actor
  • Log tool calls for debugging
Warning

Don'ts:

  • Hardcode API keys in code
  • Create a new session for each request
  • Assume a tool is available — check the advertised tools/list for the session
  • Make synchronous requests that block your workflow
  • Share API keys across teams (each key exposes its whole project)

Troubleshooting

"API key required"

Missing or malformed Authorization header. Ensure the header is present and the format is correct.

"Invalid API key"

Key doesn't match any project. Copy it again from Settings → Project → API keys, and check that the MCP URL matches the project's region.

"Too many requests"

The project's tool-call budget (60 per minute by default) is used up, across all of its sessions. Wait for Retry-After and reduce call frequency.

"Session not found" / "Unknown sessionId"

Session was torn down, expired after 10 idle minutes, or the connection closed. Initialize a new session (omit the mcp-session-id header on the next initialize).

"Session belongs to a different project"

The session was created with a different key. Create a new session with the key you're using now.

A tool or parameter returns not_enabled

Some advertised parameters, such as fields on search_traces and selective-context options on get_trace_context, are not enabled yet. Omit them.

A tool is missing from tools/list

Tools are enabled per deployment and authentication scope. Initialize an authenticated session and call tools/list to see the tools that session can use. Call ping to check connectivity. Refresh your client if it is pinned to an older tool list; the hosted /mcp/health endpoint is not a public, unauthenticated check.


Next Steps

On this page

Ask Neatlogs AI

Answers from the docs

How can I help?

Ask anything about instrumenting, tracing, or the Neatlogs dashboard.