# Create context

URL: https://docs.hanzo.ai/docs/openapi/code/post-code-context

> Packs the most relevant code for a query into a token budget — THE primitive for a coding agent that has to decide what to put in a prompt.

`POST /v1/code/context`

> [Code →](https://docs.hanzo.ai/docs/openapi/code) · [All API references →](https://docs.hanzo.ai/docs/openapi) · [Get started →](https://docs.hanzo.ai/docs/guides)

|               |                                        |
| ------------- | -------------------------------------- |
| **Address**   | `https://api.hanzo.ai/v1/code/context` |
| **Method**    | `POST`                                 |
| **Operation** | `post_code_context`                    |
| **Auth**      | `Authorization: Bearer $HANZO_API_KEY` |

Packs the most relevant code for a query into a token budget — THE
primitive for a coding agent that has to decide what to put in a prompt. It
retrieves seed spans, expands each with the definitions it calls and its key
callers, then greedily fills the budget, so the answer is a coherent slice of
the codebase rather than a list of disconnected matches. The top match is
always included, truncated if it alone overflows, so a matched query never
comes back empty. A retrieval outage answers 200 with an empty bundle rather
than a 5xx.

## Request

3 fields, body `application/json` (required).

| Field          | In   | Type            | Required | Description                               |
| -------------- | ---- | --------------- | -------- | ----------------------------------------- |
| `budgetTokens` | body | integer (int64) | —        | BudgetTokens caps the bundle's size.      |
| `query`        | body | string          | —        | Query is what to retrieve context for.    |
| `repo`         | body | string          | —        | Repo narrows retrieval to one repository. |

## Response

| Status    | Body               | Meaning |
| --------- | ------------------ | ------- |
| `200`     | code.ContextBundle | ok      |
| `default` | problem-details    | refused |

`200` body — 16 fields.

| Field             | In   | Type            | Always | Description                                                                                                                                                                                                                                                                                                                     |
| ----------------- | ---- | --------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `budgetTokens`    | body | integer (int64) | —      | BudgetTokens is the ceiling the caller asked for.                                                                                                                                                                                                                                                                               |
| `capped`          | body | boolean         | —      | Capped is true when the semantic tier stopped at its scan cap — it compares a query with at most 50000 stored vectors — with more left unread, so code past the cap could not be picked by meaning.                                                                                                                             |
| `query`           | body | string          | —      | Query is the ask this bundle was packed for, echoed back so a cached or forwarded bundle still says what it answers.                                                                                                                                                                                                            |
| `repo`            | body | string          | —      | Repo narrows the retrieval to one repository.                                                                                                                                                                                                                                                                                   |
| `spans`           | body | code.Span\[]    | —      | Spans are the packed chunks, most relevant first, each expanded with the definitions it calls and its notable callers.                                                                                                                                                                                                          |
| `spans[].endLine` | body | integer (int64) | —      | EndLine is the last line of the span, inclusive.                                                                                                                                                                                                                                                                                |
| `spans[].file`    | body | string          | —      | File is the path inside the repo, relative to its root and never absolute.                                                                                                                                                                                                                                                      |
| `spans[].kind`    | body | string          | —      | Kind is what the indexer decided this chunk IS — "func", "method", "type", "struct", "interface", "var", "const", or "block" for a run of code that declares nothing.                                                                                                                                                           |
| `spans[].line`    | body | integer (int64) | —      | Line is where the span starts, 1-based, as an editor counts.                                                                                                                                                                                                                                                                    |
| `spans[].repo`    | body | string          | —      | Repo is the indexed repository the span was found in, as it was indexed ("owner/name").                                                                                                                                                                                                                                         |
| `spans[].role`    | body | string          | —      | context: match \| definition \| caller                                                                                                                                                                                                                                                                                          |
| `spans[].score`   | body | number (double) | —      | Score ranks this span against the OTHERS IN THE SAME RESPONSE and means nothing across responses or between tiers: the hybrid tier's number is a reciprocal-rank fusion sum (Σ 1/(60+rank), so tenths at best), the symbol tier's is a descending position count, and the text and semantic tiers pass through bm25 and cosine. |
| `spans[].snippet` | body | string          | —      | Snippet is the code itself: a bounded excerpt on /search, the whole chunk on /context — which is why the same type serves both and why a /context span is the one an agent pastes into its window.                                                                                                                              |
| `spans[].symbol`  | body | string          | —      | Symbol is the declared name, when the span declares one.                                                                                                                                                                                                                                                                        |
| `spans[].tier`    | body | string          | —      | Tier is which retrieval produced the span: "hybrid" (the default — all three fused), "text" (trigram/FTS), "regex", "semantic" (vector), or "symbol".                                                                                                                                                                           |
| `usedTokens`      | body | integer (int64) | —      | UsedTokens is what the returned spans actually cost, by the same estimate the packer used (roughly one token per four characters — an estimate, not a tokenizer's count, so size a real window with headroom).                                                                                                                  |

Failure carries the platform error shape — see [Errors](https://docs.hanzo.ai/docs/errors).

## Examples

**CLI**

```bash
hanzo code context
```

**SDK**

**.ts**

```ts
import { Configuration, CodeApi } from 'hanzoai';

const api = new CodeApi(new Configuration({ accessToken: process.env.HANZO_API_KEY }));
const { data } = await api.postCodeContext({ budgetTokens: 0, query: "<query>" });
```

**.py**

```python
from hanzoai.cloud import ApiClient, Configuration
from hanzoai.cloud.api import CodeApi

client = ApiClient(Configuration(access_token=os.environ["HANZO_API_KEY"]))
result = CodeApi(client).post_code_context(budget_tokens=0, query="<query>")
```

**.go**

```go
cfg := hanzoai.NewConfiguration()
cfg.AddDefaultHeader("Authorization", "Bearer "+os.Getenv("HANZO_API_KEY"))
client := hanzoai.NewAPIClient(cfg)

resp, _, err := client.CodeAPI.PostCodeContext(context.Background()).Execute()
if err != nil {
	return err
}
```

**.rs**

```rust
use hanzo_client::apis::{configuration::Configuration, code_api};

let mut cfg = Configuration::new();
cfg.bearer_access_token = std::env::var("HANZO_API_KEY").ok();

let result = code_api::post_code_context(&cfg, Default::default()).await?;
```

**.java**

```java
import ai.hanzo.cloud.ApiClient;
import ai.hanzo.cloud.api.CodeApi;

ApiClient client = new ApiClient();
client.setBearerToken(System.getenv("HANZO_API_KEY"));

var result = new CodeApi(client).postCodeContext();
```

**HTTP**

```bash
curl -X POST https://api.hanzo.ai/v1/code/context \
  -H "Authorization: Bearer $HANZO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
       "budgetTokens": 0,
       "query": "<query>"
     }'
```

**MCP**

MCP reaches **code** through the `code` tool, which names its 7 operations with its own verbs — this one among them, under a name only MCP declares. `describe` explains any of them:

```bash
curl -X POST https://api.hanzo.ai/v1/mcp \
  -H "Content-Type: application/json" \
  -d '{
       "jsonrpc": "2.0",
       "id": 1,
       "method": "tools/call",
       "params": {
         "name": "describe",
         "arguments": {
           "op": "get_code_ask"
         }
       }
     }'
```

---

[Code API](https://docs.hanzo.ai/docs/openapi/code) · [All Hanzo APIs](https://docs.hanzo.ai/docs/openapi) · [Interactive reference](https://docs.hanzo.ai/docs/openapi/reference)
