> For the complete documentation index, see [llms.txt](https://docs.codna.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.codna.ai/guides/mcp.md).

# MCP Server

`codna mcp` runs Codna as a [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server over stdio, exposing Codna's triage, fix, and security-reachability capabilities as native tools that any MCP client can call. Use it when you want Codna inside your editor or chat client — Cursor, Claude Desktop, or your own agent — instead of (or alongside) the `codna` command line documented in CLI.

```bash
codna mcp
```

Run bare, `codna mcp` (equivalent to `codna mcp start`) launches a FastMCP server named `codna` over standard input/output — the transport Cursor and Claude Desktop expect. It stays in the foreground waiting for a client and prints nothing on success; the client spawns it from the config below, so you rarely run it by hand. It also accepts `--repo <repo>` to set a default repo for the tools, and an `install` subcommand (below) that writes a client's config for you.

## Installation

The MCP server is an optional channel, installed with the `mcp` extra:

```bash
pip install "codna[mcp]"
```

This adds the `mcp` package on top of a normal `pip install codna`. It's kept out of the base install because `mcp` pulls a small web stack (`starlette`, `uvicorn`) that CLI and CI use don't need. If you already have Codna, just add the extra:

```bash
pip install --upgrade "codna[mcp]"
```

If you run `codna mcp` without the extra, Codna tells you exactly what to install — the base `codna` command, triage, fix, and security features work without it.

## Configuration

The server and the CLI use the same packaged local runtime: in-process Algenta repository intelligence, local step artifacts, bundled Telys, and Codna's internal local agent runtime when verified planning needs a model. Because the MCP client spawns `codna mcp` as a child process, set credentials in the `env` block of the client configuration; the server inherits nothing else.

| Variable                                                  | Purpose                                                               | Default |
| --------------------------------------------------------- | --------------------------------------------------------------------- | ------- |
| `CODNA_API_KEY`                                           | Your Codna API key.                                                   | —       |
| `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / `GEMINI_API_KEY` | Provider key for model-backed fixes and reviews.                      | —       |
| `CODNA_MCP_DEFAULT_REPO`                                  | Default repo for tools when the caller passes `.` (same as `--repo`). | `.`     |

## Exposed tools

The server registers four tools. Each one returns a JSON **string** (pretty-printed, two-space indent) and is wrapped so a failure never crashes the server: errors come back as a plain string of the form `codna_<tool> error: <message>`, which the client surfaces as the tool result.

### `codna_triage`

Understands a repository and locates the code relevant to an issue. Read-only and deterministic — 0 LLM tokens.

| Parameter | Type   | Default | Description                                                                                                                                                 |
| --------- | ------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `repo`    | string | `.`     | A local path or a git URL. A local directory is read directly by local Algenta SDK/core; an `http(s)://` or `.git` URL is registered as a GitHub connector. |
| `issue`   | string | `""`    | Optional description of what to look for. When empty, Codna uses `"Map this repository and locate its most relevant code."`                                 |

Returns a JSON object with these fields:

```json
{
  "suspect_files": [
    "src/auth/session.py",
    "src/auth/tokens.py"
  ],
  "reduction_ratio": 312.0,
  "raw_repo_tokens": 1842030,
  "evidence_bundle_tokens": 5904
}
```

| Field                    | Meaning                                                                                  |
| ------------------------ | ---------------------------------------------------------------------------------------- |
| `suspect_files`          | The files Codna identified as most relevant to the issue.                                |
| `reduction_ratio`        | How much smaller the evidence bundle is than the raw repo (e.g. `312.0` = 312x smaller). |
| `raw_repo_tokens`        | Estimated token count of the whole repository.                                           |
| `evidence_bundle_tokens` | Token count of the reduced bundle handed to an agent.                                    |

### `codna_fix`

Finds and fixes a bug. Runs the full Codna agent plus the engine and a deterministic risk simulation.

| Parameter | Type    | Default                          | Description                                                                                                                                                                              |
| --------- | ------- | -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `repo`    | string  | (required)                       | A local path or a git URL.                                                                                                                                                               |
| `issue`   | string  | (required)                       | What is broken — e.g. the failing test or the observed behavior.                                                                                                                         |
| `ref`     | string  | `""`                             | Optional branch, tag, or commit to check out before analysis.                                                                                                                            |
| `open_pr` | boolean | `false`                          | When `false`, plan only. When `true`, open a pull request; requires a git URL for `repo`, a non-empty `issue`, and `GITHUB_TOKEN` or `CODNA_GITHUB_TOKEN` in the MCP server environment. |
| `model`   | string  | `repository.verified_agentic_v1` | Optional provider-qualified planner model, e.g. `openai/gpt-5`.                                                                                                                          |

Returns a JSON object:

```json
{
  "root_cause": "Session token expiry compared against a naive datetime, so tokens never expire under UTC.",
  "impacted_symbols": ["Session.is_expired", "TokenStore.purge"],
  "blast_radius": "low",
  "confidence": 0.91,
  "patch_ref": "patch:sha256:9f2c…",
  "model": "repository.verified_agentic_v1",
  "cost_usd": 0.072
}
```

| Field              | Meaning                                              |
| ------------------ | ---------------------------------------------------- |
| `root_cause`       | The engine's explanation of why the bug occurs.      |
| `impacted_symbols` | Functions/classes the fix touches.                   |
| `blast_radius`     | Qualitative scope of the change.                     |
| `confidence`       | Planner confidence in the fix, `0.0`–`1.0`.          |
| `patch_ref`        | Reference to the generated patch held by the engine. |
| `model`            | The runtime planner model that produced the plan.    |
| `cost_usd`         | Planner cost for the run.                            |

{% hint style="info" %}
By default, `codna_fix` **plans** the fix and returns a `patch_ref`; it does not apply patches to a local checkout. Set `open_pr=true` only when the repo is a git URL and the MCP server environment contains a write-capable GitHub token. To apply a patch directly to a local checkout, use `codna fix --apply` from the command line (see CLI).
{% endhint %}

With `open_pr=true`, the tool returns the opened PR URL instead of a local patch reference:

```json
{
  "root_cause": "Checkout total subtracts discounts twice, so carts with coupons underflow.",
  "confidence": 0.78,
  "pull_request_url": "https://github.com/acme/shop/pull/482",
  "status": "opened_pull_request",
  "model": "repository.verified_agentic_v1"
}
```

### `codna_secure`

Proves which scanner findings are reachable. Ingests a SARIF report (CodeQL, Semgrep, Snyk, or Trivy), classifies each finding (exploitable, production-reachable, unreachable, or unknown) via the engine, and reports which are autofix-eligible. Read-only and 0 LLM tokens.

| Parameter    | Type   | Default    | Description                                                                                                  |
| ------------ | ------ | ---------- | ------------------------------------------------------------------------------------------------------------ |
| `repo`       | string | `.`        | A local path or a git URL.                                                                                   |
| `sarif_path` | string | (required) | Path to the scanner's SARIF output. If empty, the tool returns `codna_secure error: sarif_path is required`. |
| `ref`        | string | `""`       | Optional branch, tag, or commit.                                                                             |

The SARIF report must carry complete provenance. If it does not, the tool returns `codna_secure error: SARIF provenance incomplete: …` listing the missing fields, and does nothing else. On success it returns:

```json
{
  "counts": {
    "exploitable": 1,
    "production-reachable": 2,
    "unreachable": 5,
    "unknown": 1
  },
  "autofix_eligible": 3,
  "findings": [
    {
      "rule_id": "py/sql-injection",
      "kind": "sql-injection",
      "classification": "exploitable",
      "eligible": true,
      "reason": "autofix-eligible"
    },
    {
      "rule_id": "py/clear-text-logging",
      "kind": "sensitive-data",
      "classification": "unreachable",
      "eligible": false,
      "reason": "no reachable path from an entry point"
    }
  ]
}
```

| Field              | Meaning                                                                         |
| ------------------ | ------------------------------------------------------------------------------- |
| `counts`           | A map of classification to count across all findings.                           |
| `autofix_eligible` | Total number of findings Codna deems autofix-eligible.                          |
| `findings[]`       | Per-finding `rule_id`, `kind`, `classification`, `eligible` flag, and `reason`. |

{% hint style="info" %}
The MCP `codna_secure` tool classifies and reports only. To remediate eligible findings or open security fix PRs, use `codna secure --fix` / `--open-pr` from the command line — see Security Autofix.
{% endhint %}

### `codna_recall`

Recalls code from local on-device Telys memory. Read-only and local; it does not call the model or mutate the repository.

| Parameter  | Type    | Default    | Description                                                                                           |
| ---------- | ------- | ---------- | ----------------------------------------------------------------------------------------------------- |
| `repo`     | string  | `.`        | Local repository path to index/search.                                                                |
| `query`    | string  | (required) | Natural-language or symbol query. If empty, the tool returns `codna_recall error: query is required`. |
| `service`  | string  | `""`       | Optional service/module filter.                                                                       |
| `language` | string  | `""`       | Optional language filter.                                                                             |
| `final_k`  | integer | `8`        | Maximum number of recalled results.                                                                   |

Returns a JSON object with ranked symbols, an explanation payload, and the number of candidates searched:

```json
{
  "symbols": [
    {
      "id": "src/checkout/pricing.py::apply_discount",
      "path": "src/checkout/pricing.py",
      "name": "apply_discount",
      "score": 0.93
    }
  ],
  "explain": {
    "query": "checkout discount calculation"
  },
  "candidate_count": 41
}
```

## Install into a client

Instead of hand-editing the config, let Codna write the client entry for you:

```bash
codna mcp install --client cursor            # writes ~/.cursor/mcp.json
codna mcp install --client cursor --project  # writes ./.cursor/mcp.json (repo-scoped)
codna mcp install --client claude            # writes the Claude Desktop config
```

* `--client cursor|claude` (required) picks the client.
* `--project` writes the project-local Cursor config instead of the user config (Cursor only).
* `--repo <repo>` bakes a default repo into the server entry.

The command merges a `codna` server into `mcpServers` (preserving any existing servers), writes atomically, and prints a JSON summary with the resolved config `path`. It does **not** write credentials — set `CODNA_API_KEY` in the config's `env` block afterward. To configure a client by hand instead, use the blocks below.

## Editor setup

Both clients use the same `codna` server block — only the config file location differs. Pick your client below.

{% tabs %}
{% tab title="Cursor" icon="laptop-code" %}
Add a `codna` entry to your MCP servers configuration. Use `~/.cursor/mcp.json` for all projects, or `.cursor/mcp.json` inside a project for project-scoped access:

{% code title=".cursor/mcp.json" lineNumbers="true" %}

```json
{
  "mcpServers": {
    "codna": {
      "command": "codna",
      "args": ["mcp"],
      "env": {
        "CODNA_API_KEY": "your-codna-api-key"
      }
    }
  }
}
```

{% endcode %}

After saving, reload Cursor's MCP servers (Settings → MCP, or restart). The `codna_triage`, `codna_fix`, `codna_secure`, and `codna_recall` tools then become available to the agent.
{% endtab %}

{% tab title="Claude Desktop" icon="message" %}
Add the same block to your Claude Desktop configuration file:

* macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
* Windows: `%APPDATA%\Claude\claude_desktop_config.json`

{% code title="claude\_desktop\_config.json" lineNumbers="true" %}

```json
{
  "mcpServers": {
    "codna": {
      "command": "codna",
      "args": ["mcp"],
      "env": {
        "CODNA_API_KEY": "your-codna-api-key"
      }
    }
  }
}
```

{% endcode %}

Restart Claude Desktop to load the server. The four Codna tools then appear in the tools (plug) menu in the message composer.
{% endtab %}
{% endtabs %}

{% hint style="warning" %}
`"command": "codna"` requires the `codna` executable to be on the `PATH` of the process that launches the MCP client — which is often **not** your shell's `PATH` (GUI apps on macOS frequently ignore it). If the client cannot find it, set `command` to the absolute path of the binary, e.g. the output of `which codna`:

```json
{
  "mcpServers": {
    "codna": {
      "command": "/Users/you/.venvs/codna/bin/codna",
      "args": ["mcp"],
      "env": {
        "CODNA_API_KEY": "your-codna-api-key"
      }
    }
  }
}
```

{% endhint %}

## Example prompts

Once a client is connected, you drive Codna in natural language; the client picks the tool and fills the parameters. Realistic prompts:

```
Use codna to triage this repo and tell me where the auth code lives.
```

```
codna_triage the github.com/acme/api repo for "checkout returns 500 on empty cart"
```

```
The test tests/test_session.py::test_expiry is failing — use codna to find and fix the bug.
```

```
Run codna_fix on this repository for the issue "JWT refresh tokens never expire" and show me the root cause and confidence.
```

```
I have a CodeQL report at ./results.sarif — use codna to tell me which findings are actually reachable.
```

```
codna_secure: classify the findings in /tmp/semgrep.sarif and list only the autofix-eligible ones.
```

## End-to-end: Cursor on a local repo

{% stepper %}
{% step %}

#### Install Codna with the MCP extra

```bash
pip install "codna[mcp]"
```

{% endstep %}

{% step %}

#### Confirm the binary and its path

```bash
which codna
```

```
/Users/you/.venvs/codna/bin/codna
```

{% endstep %}

{% step %}

#### Create `.cursor/mcp.json` in the repository

Point `command` at the absolute path you just printed so the GUI launcher can find the binary:

{% code title=".cursor/mcp.json" lineNumbers="true" %}

```json
{
  "mcpServers": {
    "codna": {
      "command": "/Users/you/.venvs/codna/bin/codna",
      "args": ["mcp"],
      "env": {
        "CODNA_API_KEY": "ck_live_xxx"
      }
    }
  }
}
```

{% endcode %}
{% endstep %}

{% step %}

#### Reload MCP servers in Cursor

The `codna` server should show four tools.
{% endstep %}

{% step %}

#### Drive Codna from the agent panel

In the agent panel, type:

```
Use codna_triage on . and summarize the suspect files.
```

Codna returns the suspect files and the context-reduction ratio, and the agent summarizes them. From there, ask it to `codna_fix` a specific issue. Use `open_pr=true` for a git URL when you want Codna to open a PR, or take the returned `patch_ref` to the CLI to apply it locally.
{% endstep %}
{% endstepper %}

## Verifying the server

You can confirm the server starts and the credentials resolve by running it directly. It will block waiting for a client — that is success:

```bash
CODNA_API_KEY=your-codna-api-key codna mcp
```

Nothing is printed and the process does not exit. Press Ctrl-C to stop. To confirm the client side, check your MCP client's logs for the `codna` server connecting and discovering four tools.

## Troubleshooting

<details>

<summary>Server not detected / tools missing in the client</summary>

The client could not spawn `codna mcp`. Most often `codna` is not on the launching process's `PATH`. Fix by pointing `command` at the absolute path from `which codna` (see the editor-setup warning above), then reload/restart the client. Verify the binary runs at all:

```bash
codna --version
```

```
codna 0.1.43
```

</details>

<details>

<summary><code>ModuleNotFoundError: No module named 'mcp'</code></summary>

Current `codna` releases include MCP in the base install. This error means the MCP client is launching a stale executable, a different virtualenv, or an older editable checkout. Verify the exact binary the client launches:

```
ModuleNotFoundError: No module named 'mcp'
```

```bash
which codna
codna --version
python -m pip install --upgrade codna
```

Make sure you upgrade the **same** interpreter the MCP `command` path points at. A mismatched venv is the usual cause of "I installed it but it still fails."

</details>

<details>

<summary>Every tool returns a no-API-key / engine error</summary>

The `env` block was not delivered to the spawned process, or the key is wrong. Each tool calls the same client the CLI uses, so a missing key surfaces as a tool error string such as:

```
codna_triage error: no API key — set CODNA_API_KEY (your codna key).
```

Confirm `CODNA_API_KEY` is present in the server's `env` block (not just in your shell — GUI clients do not inherit your shell environment), reload the client, and re-test directly:

```bash
CODNA_API_KEY=your-codna-api-key codna mcp
```

</details>

<details>

<summary><code>codna_secure</code> rejects the SARIF</summary>

Two specific errors come from this tool:

```
codna_secure error: sarif_path is required
```

Pass a `sarif_path`. And:

```
codna_secure error: SARIF provenance incomplete: <missing fields>
```

The report lacks the provenance Codna requires to bind findings to a commit. Re-run your scanner so its SARIF includes complete provenance (commit/run metadata), then retry.

</details>

<details>

<summary><code>repo</code> is neither a directory nor a URL</summary>

If `repo` is not an existing local directory and not an `http(s)://` or `.git` URL, the underlying register step errors with:

```
'<repo>': not a local directory or a git URL.
```

Pass an absolute/relative path to a real checkout, or a git URL.

</details>

## Next steps

* **CLI** — the `codna` command, including `codna fix --apply` / `--open-pr` to act on a plan.
* **Security Autofix** — `codna secure` reachability proofs and remediation PRs.
* **Configuration** — full environment-variable precedence plus local runtime and key settings.
* **GitHub Action** — opening fix PRs from CI.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.codna.ai/guides/mcp.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
