# OpenCode

> Connect OpenCode to Last9's MCP server to query production observability data — logs, traces, metrics, and alerts — directly from your terminal coding session.

Source: https://last9.io/docs/integrations/opencode/

[OpenCode](https://opencode.ai) is an open-source AI coding agent built for the terminal. It supports the Model Context Protocol (MCP), which means you can connect it to Last9's MCP server and give the agent direct access to your production observability data — logs, traces, metrics, exceptions, and alerts — without leaving your terminal session.

Ask OpenCode questions like _"Why is payment-service throwing 500s right now?"_ or _"What are the slowest database queries in prod?"_ and the agent will query Last9 in real time to answer.

## Prerequisites

- **OpenCode** — installed and working (`opencode --version`)
- **Last9 account** — with observability data flowing in via OpenTelemetry
- **Org slug** — found in your Last9 URL: `https://app.last9.io/<org_slug>/...`

## Setup

1. **Locate or create your OpenCode config file**

   OpenCode reads configuration from `opencode.json` (or `opencode.jsonc`) in your project root or home directory. If you don't have one yet, create it:

   ```bash
   touch ~/opencode.json
   ```

2. **Add the Last9 MCP server**

**Remote (recommended)**

   Add Last9 as a remote MCP server using OAuth. Replace `<org_slug>` with your organization slug:

   ```json
   {
     "$schema": "https://opencode.ai/config.json",
     "mcp": {
       "last9": {
         "type": "remote",
         "url": "https://app.last9.io/api/v4/organizations/<org_slug>/mcp",
         "enabled": true
       }
     }
   }
   ```

   Then authenticate:

   ```bash
   opencode mcp auth last9

   ```

   This opens a browser window where you log in with your Last9 account and authorize access. The OAuth token is stored locally — you only need to do this once.

**Local binary**

   If you prefer running the MCP server locally (useful for air-gapped environments or avoiding OAuth):

   **Install the binary:**

   ```bash
   # macOS / Linux via Homebrew
   brew tap last9/tap && brew install last9-mcp

   # Cross-platform via npm
   npm install -g @last9/mcp-server@latest

   ```

   **Get a Refresh Token** from [API Access](https://app.last9.io/settings/api-access) (admin required).

   **Configure OpenCode:**

   ```json
   {
     "$schema": "https://opencode.ai/config.json",
     "mcp": {
       "last9": {
         "type": "local",
         "command": ["last9-mcp"],
         "enabled": true,
         "environment": {
           "LAST9_REFRESH_TOKEN": "<your_refresh_token>"
         }
       }
     }
   }
   ```

3. **Verify the connection**

   Start OpenCode and check that the Last9 tools are available:

   ```bash
   opencode
   ```

   Once inside a session, ask:

   ```
   What exceptions occurred in the last hour?
   ```

   OpenCode will invoke the Last9 MCP server and return results directly in your terminal.

## Example Use Cases

### Debug production exceptions

```
I'm seeing errors from user-service in prod. What's the root cause?
```

OpenCode calls `get_exceptions` and `get_service_performance_details` to surface error details, stack traces, and related performance signals.

### Investigate slow endpoints

```
Which API endpoints are slowest in payment-service right now?
```

OpenCode calls `get_service_operations_summary` and `prometheus_range_query` to break down p95 latency by endpoint.

### Correlate errors with deployments

```
We had a spike in errors around 3pm. Was there a deployment at that time?
```

OpenCode calls `get_change_events` to find deployments and correlates them with error rate data.

### Surface slow database queries

```
What are the slowest PostgreSQL queries hitting orders-db in the last 30 minutes?
```

OpenCode calls `get_database_slow_queries` and `get_database_queries` to return query patterns ranked by duration.

### Check active alerts

```
Are there any firing alerts right now?
```

OpenCode calls `get_alerts` to list currently active alerts with severity and firing timestamps.

## Configuration reference

The `mcp` block in `opencode.json` accepts these fields per server:

| Field         | Type                    | Description                                                                       |
| ------------- | ----------------------- | --------------------------------------------------------------------------------- |
| `type`        | `"remote"` \| `"local"` | `remote` connects to a hosted MCP endpoint; `local` spawns a subprocess           |
| `url`         | string                  | Remote MCP endpoint URL (required when `type` is `remote`)                        |
| `command`     | string[]                | Command and arguments to start the local binary (required when `type` is `local`) |
| `enabled`     | boolean                 | Set to `false` to temporarily disable without removing the config                 |
| `environment` | object                  | Environment variables passed to the local subprocess                              |

:::tip
You can toggle Last9 off for specific projects by setting `"enabled": false` in a project-level `opencode.json`. OpenCode merges project and global configs, with project settings taking precedence.
:::

:::caution
MCP servers add tool definitions to the model's context window. If you enable many MCP servers simultaneously, token usage increases. Last9's server is lightweight — it registers tools on demand — but keep this in mind when combining multiple servers.
:::

## Available tools

Once connected, OpenCode can use all Last9 tools. For the full list and parameters, see the [Last9 MCP](/docs/integrations/mcp/#available-tools) reference.

---

## Troubleshooting

**Last9 tools not showing up in OpenCode**

- Confirm `"enabled": true` in your `opencode.json`
- Run `opencode mcp auth last9` if using the remote type and you haven't authenticated yet
- Check that your org slug in the URL is correct (no trailing slash, no extra path segments)

**OAuth flow fails or redirects to a 404**

- Log in to [app.last9.io](https://app.last9.io) in your browser first, then re-run `opencode mcp auth last9`

**"No data returned" for queries**

- Make sure your services are sending telemetry to Last9 via the [OpenTelemetry integration](https://app.last9.io/integrations?integration=OpenTelemetry)
- Try broadening the time range in your question ("last 2 hours" instead of "last 15 minutes")

**Local binary: authentication errors**

- Verify `LAST9_REFRESH_TOKEN` is set correctly in the `environment` block
- Regenerate the token from [API Access](https://app.last9.io/settings/api-access) if it has expired

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