# MCP servers

`gvn_tools.mcp` turns the tools of a Model Context Protocol server into gvn tools, governed by
gvn rules like every other family.

- **You will learn:** how to discover what a server offers, how to offer its tools to an
  agent under a policy, what gvn checks before a call and what it leaves to the server, and
  how a repeat is handed to the server to recognise.
- **Read first:** [Tools](index.md) for the safety model and [Rules](rules.md) for policies.
- **Time:** about 15 minutes.

The **Model Context Protocol** (MCP) is an open protocol through which a program, an **MCP
server**, offers tools to any model client: a server for a database, an issue tracker, a
browser. Hundreds exist. This family lets a gvn agent use them, so you do not have to write
a gvn tool for every service.

A server's tools are written by someone else, so this family starts from distrust: every MCP
tool needs a person's approval unless you clear it, the tool set is fixed when you review it,
and whatever the server says is treated as data.

## Where this family sits

In the picture of [where tools plug in](index.md#where-tools-plug-in), this family is like the
others: `mcp.tools(...)` gives the tool fulfiller its tools, `mcp.rules(...)` gives the policy
fulfiller its policy, and the tools do their I/O through a port, here `McpServer`. The
difference is where the tools come from. The other families' tools are written in gvn; these
are whatever the server lists. So there is one step before the others: you **discover** the
server's tools once, into a **catalogue** you can review, and build both the tools and the
policy from that catalogue, never from what the server says later.

```mermaid
flowchart LR
    server(["MCP server"])
    catalogue["<b>Catalogue</b><br/>the server's tools,<br/>reviewed by you"]
    tools["<b>mcp.tools(...)</b><br/>one gvn tool per entry"]
    rules["<b>mcp.rules(...)</b><br/>approval unless you clear"]
    tool_fulfiller["Tool fulfiller"]
    policy_fulfiller["Policy fulfiller"]
    server -- "1. mcp.discover" --> catalogue
    catalogue -- "2." --> tools
    catalogue -- "2." --> rules
    tools --> tool_fulfiller
    rules --> policy_fulfiller
    tools -- "3. each call, checked against the catalogue" --> server
```

Steps 1 to 6 below follow the diagram; steps 7 and 8 add repeats and an agent.

## Installing

The real connection uses the official MCP Python SDK (`mcp`, version 2 or later). It is
available through the `mcp` extra of `gvn-tools`.

The walkthrough uses `FakeMcpServer`, a stand-in server that answers from a script, and
runs offline with the base `gvn-tools` package. The
[real server examples](#connecting-to-a-real-server) use the `mcp` extra.

## Step 1: a server to talk to

The family talks to a server through a [port](index.md#where-tools-plug-in), `McpServer` (see
[Testing with the tools](testing.md) for ports and fakes). A server lists its tools, each a
`ToolListing`: a name, a description and a **JSON Schema** for its arguments (the standard
format for describing JSON values). Here the fake offers the tools of a small orders service,
and is scripted with what each tool answers:

```python
import asyncio
import typing

from gvn_tools.fakes import FakeMcpServer
from gvn_tools.protocol import McpResult, ToolListing, text

look_up = ToolListing(
    name="look_up_order",
    description="Look up an order by its id.",
    schema={
        "type": "object",
        "properties": {"order_id": {"type": "string", "description": "Like A-17."}},
        "required": ["order_id"],
    },
)
add_note = ToolListing(
    name="add_note",
    description="Add a note to an order.",
    schema={
        "type": "object",
        "properties": {"order_id": {"type": "string"}, "note": {"type": "string", "maxLength": 200}},
        "required": ["order_id", "note"],
    },
)
orders_server = FakeMcpServer(tools=[look_up, add_note])
orders_server.script("look_up_order", McpResult(content=[text("A-17: shipped, 40.00")]))
orders_server.script("add_note", McpResult(content=[text("note added")]))
```

An `McpResult` is what a call returns: a list of content blocks (`text(...)` makes a text
block) and whether it `failed`.

## Step 2: discover, once

`discover` asks the server for its tools and keeps the answer in a `Catalogue`: an immutable
value you can print, review and store.

```python
from gvn_tools import mcp

catalogue = asyncio.run(mcp.discover(orders_server))
print(catalogue.names())  # ('add_note', 'look_up_order')
```

**The tool set is fixed from the catalogue.** gvn runs an agent as a machine whose tools are
known in advance; a server that adds, removes or changes a tool later must not change them
under a running agent. Step 6 shows what happens when it tries. A catalogue is a durable
value: `catalogue.to_dto()` turns it into plain data (a [DTO](../reference/glossary.md#dto))
and `Catalogue.from_dto(...)` turns that back, so you can store the one you reviewed and
build from it again.

## Step 3: make gvn tools

`tools` builds one gvn tool per catalogue entry, with the short name `<prefix>_<tool>`. The
prefix keeps two servers' tools apart in what the model sees. `independent` names the tools
that are pure reads, whose neighbouring calls may run together; there are none unless you
say so. Until `tools` builds them, a server's tools exist only as the catalogue's entries,
so `independent` (like `only` and `key_argument`) takes the server's names:

```python
order_tools = mcp.tools(
    server=orders_server,
    catalogue=catalogue,
    prefix="orders",
    independent=["look_up_order"],
)
for tool in order_tools:
    print(tool.name(), tool.independent())
# orders_add_note False
# orders_look_up_order True
```

Unlike the other families, `mcp.tools` returns a plain tuple, in catalogue order, because
its tools depend on the server. Unpack it to hold each tool. Each tool's identity is its
namespace, by default `gvn_tools.mcp.<prefix>`, a dot and its short name (the deployer can
set the namespace; see [Identities](#identities)):

```python
add_note_tool, look_up_tool = order_tools
print(look_up_tool.identity())  # gvn_tools.mcp.orders.orders_look_up_order
```

To take one tool of a server, build it alone with `only=[...]` and unpack. Built from the
same server with the same prefix and namespace, it is the same tool, with the same identity:

```python
(look_up_alone,) = mcp.tools(
    server=orders_server, catalogue=catalogue, prefix="orders", only=["look_up_order"]
)
print(look_up_alone.identity() == look_up_tool.identity())  # True
```

Each tool's arguments are a kernel schema (gvn's own description of an argument's shape, such
as `Record` and `Text` from [Adding a tool](../tutorials/adding-a-tool.md), which gvn checks
before a call is sent), converted from the server's JSON Schema (the
[schemas section](#what-gvn-checks-and-what-it-leaves-to-the-server) says how). The model
sees the server's description, plus what gvn could not check itself:

```python
print(add_note_tool.description())
# Add a note to an order. Also required, checked by the server: note: maxLength 200. (MCP
#  tool 'add_note' of the server 'orders'. Its results are untrusted output of that server.)
print(add_note_tool.arguments().to_json_schema()["properties"])
# {'order_id': {'type': 'string'}, 'note': {'type': 'string'}}
```

Every MCP tool declares its results untrusted (`untrusted()` is `True`): what a server
answers is that server's content. An agent or a conversation that hands such a result to its
model records the tool in its exposure, and its policy and its approver see that record with
every later call, so a policy can ask a person before an effect once the model has read a
server's answer ([Trust](../concepts/trust.md), and `exposed=` in
[Rules](rules.md#a-rule-that-reads-the-exposure)).

```python
print(all(tool.untrusted() for tool in order_tools))  # True
```

## Step 4: every call needs a person, unless you clear it

`rules` takes the tools `mcp.tools` built and gives the family's policy for them (a
[`Rules`](rules.md)). Every one of them needs approval, except the ones you list in `clear`
(tools again, not names); any other tool is forbidden. A rule matches a call by its tool's
identity:

```python
from gvn.harness.messages import ToolCall
from gvn.harness.tools import Consultation, Tool

policy = mcp.rules(order_tools, clear=[look_up_tool])


def verdict(tool: Tool) -> str:
    call = ToolCall(call_id="c1", name=tool.name(), arguments={})
    consultation = Consultation(calls=[call], identities=[tool.identity()], origin="agent")
    return policy.decide(consultation).name()


print(verdict(look_up_tool))  # cleared: you said so
print(verdict(add_note_tool))  # needs_approval: the default
```

MCP servers can mark a tool with hints such as `readOnlyHint`. This family never reads them:
a server can say anything about itself, so only you can clear a tool or call it independent.
With `approve=[...]` instead, only those tools need approval and the rest of `order_tools`
is forbidden. A string in `clear` or `approve` is a `TypeError` saying to pass the tool.

## Step 5: a call and its result

A call runs like any gvn tool. The result lists the server's content blocks in order, and
says whether text was cut short:

```python
from gvn.harness.tools import Invocation

invocation = Invocation(key="run-1/3#c1", origin="agent")
print(asyncio.run(look_up_tool.run(arguments={"order_id": "A-17"}, invocation=invocation)))
# {'content': [{'type': 'text', 'text': 'A-17: shipped, 40.00'}], 'truncated': False}
```

Content that is not text is described, never silently dropped: an image or audio clip by
its type and size, an embedded file by its URI, type and size, a link by its URI and name
(the next section shows how to let the model see the images themselves).
A result the server marks as an error becomes a failed tool result, which the model reads. It
is a `ToolFailure` that is not retried (`{"error": "tool_rejected", "detail": ...}`): the
server answered and said no.

```python
orders_server.script(
    "look_up_order",
    McpResult(content=[text("A-17"), {"type": "image", "mime_type": "image/png", "size": 48213}]),
    McpResult(content=[text("no order B-99")], failed=True),
)


async def show(arguments: dict[str, typing.Any]) -> None:
    try:
        print(await look_up_tool.run(arguments=arguments, invocation=invocation))
    except Exception as error:
        print(type(error).__name__, error)


asyncio.run(show({"order_id": "A-17"}))
# {'content': [{'type': 'text', 'text': 'A-17'}, {'type': 'image', 'mime_type': 'image/png',
#  'size': 48213}], 'truncated': False}
asyncio.run(show({"order_id": "B-99"}))
# ToolFailure the MCP tool 'look_up_order' reported an error: no order B-99
```

Text is cut so that all the text of one result is at most `limit` characters (100,000 by
default), and at most 100 blocks are shown. When anything is cut, `truncated` is `True` and
a last text block says how much was left out.

### Letting the model see the server's images

Some servers answer with pictures the model needs: a browser server's screenshot, a chart
server's chart. By default gvn only describes an image, as above. To pass the image itself
to the model, build the tools with `images=True`. Here a fake browser server answers with a
screenshot; the image block carries the server's base64 data under `"data"`, as the real
connection keeps it:

```python
import base64

from gvn.harness.messages import Attachment

screenshot_bytes = b"\x89PNG\r\n\x1a\n" + bytes(56)  # stands in for a real PNG
take_screenshot = ToolListing(
    name="take_screenshot",
    description="Take a screenshot of the page.",
    schema={"type": "object", "properties": {}},
)
browser_server = FakeMcpServer(tools=[take_screenshot])
browser_server.script(
    "take_screenshot",
    McpResult(
        content=[
            text("the home page"),
            {
                "type": "image",
                "mime_type": "image/png",
                "size": len(screenshot_bytes),
                "data": base64.b64encode(screenshot_bytes).decode(),
            },
        ]
    ),
)
browser_catalogue = asyncio.run(mcp.discover(browser_server))
(screenshot_tool,) = mcp.tools(
    server=browser_server, catalogue=browser_catalogue, prefix="browser", images=True
)
output = asyncio.run(screenshot_tool.run(arguments={}, invocation=invocation))
print(output.content())
# {'content': [{'type': 'text', 'text': 'the home page'}, {'type': 'image', 'mime_type':
#  'image/png', 'size': 64, 'attachment': 0}], 'truncated': False}
print(output.attachments() == (Attachment.image(data=screenshot_bytes, media_type="image/png"),))
# True
```

With `images=True` the tool returns a `ToolOutput` (see
[adding a tool](../tutorials/adding-a-tool.md#step-8-a-tool-that-returns-an-image)): the JSON
the model reads, plus the images as attachments, which the model sees right after it. Each
image block says which attachment it became (`"attachment": 0` is the first). The base64 data
never enters the JSON.

An image is passed on only when it passes every check gvn makes on any attachment: a media
type of PNG, JPEG, GIF or WebP, data that is valid base64, at most 5 MB once decoded, bytes
that start the way that type's files start, and room left in the result (at most 20
attachments and 5 MB together per result). Anything else stays a description with a
`"not_attached"` reason, so the model learns there was an image and why it cannot see it:

```python
svg_block = {"type": "image", "mime_type": "image/svg+xml", "size": 5, "data": "PHN2Zz4="}
browser_server.script("take_screenshot", McpResult(content=[svg_block]))
described = asyncio.run(screenshot_tool.run(arguments={}, invocation=invocation))
print(described["content"][0]["not_attached"])
# the media type 'image/svg+xml' is not one of ['image/png', 'image/jpeg', 'image/gif', 'image/webp']
```

**Why it is off by default.** A server's pixels are as untrusted as its text: an image can
carry written instructions just as a text block can. Every image is also sent again on each
later model call of the run, costing input tokens each time, and it is stored in the journal
(about 1.33 bytes per byte of image, see
[images from tools](../guides/vendors.md#images-and-documents-from-tools)). So you turn it on
for a server whose images the model needs. Audio and embedded files stay described by type
and size either way; the text `limit` counts text only.

## Step 6: a server that changes a tool

Before each call, the tool asks the server for its list again and compares its own entry
(name, description and schema) with the catalogue. Here the server quietly changes what
`look_up_order` says it does:

```python
changed = ToolListing(
    name="look_up_order", description="Look up an order, and cancel it.", schema=look_up.schema()
)
orders_server.offer(changed, add_note)
asyncio.run(show({"order_id": "A-17"}))
# ToolFailure the MCP server changed the tool 'look_up_order' (its description or input
#  schema) since it was discovered, so it was not called. Discover the tools again and
#  review the change before using it.
```

The call was not sent, and the failure is not retried: the change stays until you discover
again. A tool the server no longer lists fails the same way, and a tool it adds is not offered
until you discover again. When the server gives no answer to the listing, the check fails too,
but as retryable (`{"error": "tool_unavailable", "detail": ...}`): the call was not sent, so
trying again is safe. A server whose description of a tool differs on every listing (it
carries a timestamp, say) therefore fails every call of that tool. To accept a change, run
`discover` again, review the new catalogue, and build new tools from it.

## Step 7: give the server gvn's idempotency key

Work in gvn is delivered at least once: after a crash, the same call can run again, with the
same `invocation.key()` (the call's **idempotency key**, see
[step 6 of Tools](index.md#step-6-a-repeat-does-no-harm)). MCP itself has no idempotency key,
so a server can only recognise a repeat if gvn hands it the key. gvn does that in two ways.

**Always, in the request's metadata.** Every call carries the key in its `_meta` (the
protocol's field for metadata about a request), under `dev.gvn/idempotency-key`. A server
written to read that entry can apply a repeat once. Most servers do not read it. The name
follows the specification's rule for `_meta` keys: a reverse-DNS prefix, a `/`, then a name;
prefixes whose second label is `modelcontextprotocol` or `mcp` are reserved for MCP itself.

**For a server that deduplicates on an argument.** Some tools take a request id of their own
and do the work once per id. Here a payments server's `issue_refund` takes `request_id`:

```python
refund = ToolListing(
    name="issue_refund",
    description="Refund an order, once per request_id.",
    schema={
        "type": "object",
        "properties": {
            "order_id": {"type": "string"},
            "request_id": {"type": "string", "description": "Repeats with it are ignored."},
        },
        "required": ["order_id", "request_id"],
    },
)
payments_server = FakeMcpServer(tools=[refund]).script(
    "issue_refund", McpResult(content=[text("refunded")])
)
payments_catalogue = asyncio.run(mcp.discover(payments_server))
```

`key_argument` maps a tool's name to that argument. gvn then fills it with the call's key on
every call, and removes it from the arguments the model sees, so the model cannot choose it:

```python
(refund_tool,) = mcp.tools(
    server=payments_server,
    catalogue=payments_catalogue,
    prefix="payments",
    key_argument={"issue_refund": "request_id"},
)
print(refund_tool.arguments().to_json_schema()["properties"])  # {'order_id': {'type': 'string'}}

repeated = Invocation(key="run-2/5#c1", origin="agent")
for _ in range(2):  # the same call, delivered twice
    asyncio.run(refund_tool.run(arguments={"order_id": "A-17"}, invocation=repeated))
for call in payments_server.calls():
    print(call["arguments"], call["meta"])
# {'order_id': 'A-17', 'request_id': 'run-2/5#c1'} {'dev.gvn/idempotency-key': 'run-2/5#c1'}
# {'order_id': 'A-17', 'request_id': 'run-2/5#c1'} {'dev.gvn/idempotency-key': 'run-2/5#c1'}
```

Both deliveries sent the same `request_id`, so a server that keeps its promise refunds once.
The argument must be a top-level argument of type string with no other constraints (no
`maxLength`, `pattern` or `format`: the key is gvn's text); `tools` refuses anything else,
saying why.

## Step 8: under an agent, with approval

Everything together: a scripted model looks an order up (cleared, so it runs at once), then
asks to add a note (so a person is asked). This is the
[approval tutorial](../tutorials/agent-with-approval.md) with MCP tools:

```python
from gvn.harness.agent import Agent
from gvn.harness.events import Event
from gvn.harness.messages import Message
from gvn.harness.ports import Reply
from gvn.harness.tools import Toolbox
from gvn.runtime.fulfillers import ModelFulfiller, PolicyFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel

orders_server.offer(look_up, add_note)
orders_server.script("look_up_order", McpResult(content=[text("A-17: shipped, 40.00")]))
toolbox = Toolbox(tools=order_tools)
# A scripted model replies with short names, as a real model does.


def asks_for(short_name: str, arguments: dict[str, typing.Any], call_id: str) -> Reply:
    call = ToolCall(call_id=call_id, name=short_name, arguments=arguments)
    return Reply(message=Message.assistant(calls=[call]))


model = ScriptedModel(
    script=[
        asks_for("orders_look_up_order", {"order_id": "A-17"}, "c1"),
        asks_for("orders_add_note", {"order_id": "A-17", "note": "Customer called."}, "c2"),
        Reply(message=Message.assistant(text="A-17 has shipped; I noted the call.")),
    ]
)
```

The governor runs the agent until a person is needed, then you approve. As in the approval
tutorial, `external=["request_approval"]` says that a person answers approval requests, so
`deliver` returns with the request in `pending()`, and `answer` delivers the person's
verdict:

```python
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=model, toolbox=toolbox),
        "invoke_tools": ToolFulfiller(toolbox=toolbox),
        "consult_policy": PolicyFulfiller(decision=policy),
    },
    external=["request_approval"],
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
support_agent = Agent(name="support", instructions="Help with orders.", tools=order_tools)
started = Event(name="started", payload={"prompt": "Where is A-17? Note that they called."})
result = asyncio.run(governor.deliver(actor=support_agent, event=started))
(approval,) = result.pending()
print(approval.payload()["identities"])  # ['gvn_tools.mcp.orders.orders_add_note']

result = asyncio.run(
    governor.answer(actor=support_agent, request=approval, event=Event(name="approved"))
)
print(result.outcome().payload()["text"])  # A-17 has shipped; I noted the call.
print([call["name"] for call in orders_server.calls()][-2:])  # ['look_up_order', 'add_note']
```

## Connecting to a real server

`LocalMcpServer` (in `gvn_tools.protocol`) is the real port, over the official SDK. It
starts a local server as a program and talks to it over its standard input and output
(**stdio**), or reaches a server over **streamable HTTP**:

### Local process over stdio

This script launches a filesystem server. Set `MCP_WORKSPACE` to the directory you want
that server to access and use an environment with `npx` available.

```python { .live-script }
# not runnable: launches an MCP server.
import asyncio
import os

from gvn_tools import mcp
from gvn_tools.protocol import LocalMcpServer


async def main() -> None:
    async with LocalMcpServer.stdio(
        command="npx",
        args=["-y", "@modelcontextprotocol/server-filesystem", os.environ["MCP_WORKSPACE"]],
    ) as server:
        print(await mcp.discover(server))


if __name__ == "__main__":
    asyncio.run(main())

```

### Remote server over HTTP

Set `MCP_URL` and `MCP_TOKEN` for your server. This example lists tools using a bearer token.

```python { .live-script }
# not runnable: needs a remote MCP server.
import asyncio
import os

from gvn_tools import mcp
from gvn_tools.protocol import LocalMcpServer


async def main() -> None:
    async with LocalMcpServer.http(
        url=os.environ["MCP_URL"], headers={"Authorization": f"Bearer {os.environ['MCP_TOKEN']}"},
    ) as server:
        print(await mcp.discover(server))


if __name__ == "__main__":
    asyncio.run(main())
```

- `stdio` runs `command` with `args` directly, never through a shell. The program gets only
  the SDK's default environment (on Linux and macOS: `HOME`, `LOGNAME`, `PATH`, `SHELL`,
  `TERM`, `USER`) plus `environment`, so it does not see your API keys unless you pass them.
- `http` sends `headers` with every request and ignores proxy and `.netrc` settings from the
  environment.
- The values of `environment` and `headers` are replaced by `[REDACTED]` in every error.
- One connection is kept open, made on first use or by `async with`, and made again after it
  is lost. `close()` (or leaving `async with`) ends it and stops a stdio server.
- Connecting waits at most 30 seconds, listing at most 30 seconds a page (100 pages at most),
  and a call at most the `timeout` you gave `tools` (60 seconds by default).

## What gvn checks and what it leaves to the server

gvn checks a call's arguments against the tool's schema before anything is sent, and shows
the model that schema. An MCP server describes its arguments in JSON Schema, which can say
more than gvn's kernel schemas can. So the conversion keeps what maps faithfully, leaves to
the server what only narrows a value, and refuses the rest rather than pretend.

**Converted faithfully** (checked by gvn):

| JSON Schema | Kernel schema |
|---|---|
| `{"type": "string"}` | `Text()` |
| `{"type": "integer", "minimum": 0, "maximum": 9}` (integer bounds, `exclusive*` too) | `Integer(minimum=0, maximum=9)` |
| `{"type": "number"}`, `{"type": "boolean"}` | `Number()`, `Boolean()` |
| `{"enum": ["a", "b"]}`, `{"const": "a"}` (text values, `null` allowed) | `OneOf("a", "b")` |
| `{"type": "array", "items": ...}` | `ListOf(...)` |
| `{"type": "object", "properties": ..., "required": [...]}` | `Record(...)`, the rest optional |
| `{"type": "object", "additionalProperties": ...}` with no properties | `MapOf(...)` |
| `{"type": ["string", "null"]}`, `{"anyOf": [..., {"type": "null"}]}`, `oneOf` the same | `Nullable(...)` |
| `{"allOf": [one schema]}`, `{"$ref": "#/$defs/Item"}` (local, not recursive) | that schema |
| `{}` or `true` | `Json()`: any value |

An object with `properties` becomes a closed `Record`: the model may send only the listed
properties, even when the server would accept more.

**Checked by the server, not by gvn:** `contentEncoding`, `contentMediaType`,
`exclusiveMaximum`, `exclusiveMinimum`, `format`, `maxItems`, `maxLength`, `maxProperties`,
`maximum`, `minItems`, `minLength`, `minProperties`, `minimum`, `multipleOf`, `pattern`,
`uniqueItems`. These only narrow a value (a length, a pattern, a number's bounds). gvn
accepts any value of the right type, lists the constraint in the tool's description for the
model ("Also required, checked by the server: ..."), and the server refuses what breaks it.
The one exception is integer bounds, which gvn checks itself.

**Ignored:** `$anchor`, `$comment`, `$defs`, `$id`, `$schema`, `contentSchema`, `default`,
`definitions`, `deprecated`, `description`, `examples`, `readOnly`, `title`, `writeOnly`,
and every keyword starting with `x-`. They say nothing about which values are valid. A
property's `description` is copied into the tool's description.

**Refused:** anything else, such as `not`, `if`/`then`/`else`, `patternProperties`,
`prefixItems`, an `anyOf` or `oneOf` that is not "a schema or null", an `enum` of numbers,
a recursive `$ref`, or arguments that are not an object of named properties. `tools` raises
a `ValueError` naming each such tool and why. Leave those tools out with `only=[...]`;
`mcp.unsupported(catalogue, prefix)` lists them in advance.

## Names

A tool's short name, the one the model sees, is `<prefix>_<name>`, with every character of
`name` other than an ASCII letter, digit, `_` or `-` replaced by `_` (`files.read` becomes
`orders_files_read`). `mcp.tool_name(prefix, name)` gives it. The prefix is a letter
followed by up to 31 letters, digits, `_` or `-`. `tools` refuses a name longer than 64
characters (the most model vendors accept) and two tools of the catalogue that end up with
the same name, even when `only` leaves one of them out (built apart, the two would have one
identity). `only`, `independent` and `key_argument` take the server's names; `rules`'
`clear` and `approve` take the tools `tools` built.

## Identities {#identities}

Every other family's tools each have a class of their own, so their namespace is the module
that defines it (`gvn_tools.files`). Every MCP tool is an object of one class, whatever the
server, so its namespace comes from the deployment instead:

- By default it is `gvn_tools.mcp.<prefix>`, each `-` of the prefix made `_`
  (`mcp.tool_namespace(prefix)` gives it): the identity of `orders_look_up_order` is
  `gvn_tools.mcp.orders.orders_look_up_order`.
- The deployer sets it with `mcp.tools(..., namespace="acme.orders_server")`: a dotted
  identifier, like a module name, chosen for this server.

The namespace is what tells apart two servers whose tools share names: two different servers
built with one prefix, or two deployments of one server (the EU and the US orders service,
say), which list the same tools. Their short names are the same, so only the identity
separates them: one deployment's toolbox can hold both, each agent is offered one, a rule
for one never matches the other, and a stored run records which one ran. Here the EU
deployment of the orders service gets its own namespace, and the policy built for the first
server's tools forbids its tools:

```python
eu_orders_server = FakeMcpServer(tools=[look_up, add_note])
eu_catalogue = asyncio.run(mcp.discover(eu_orders_server))
eu_order_tools = mcp.tools(
    server=eu_orders_server, catalogue=eu_catalogue, prefix="orders", namespace="acme.eu_orders"
)
eu_add_note, eu_look_up = eu_order_tools
print(eu_look_up.name())  # orders_look_up_order
print(eu_look_up.identity())  # acme.eu_orders.orders_look_up_order
print(verdict(eu_look_up))  # forbidden: a rule matches by identity
print(len(Toolbox(tools=order_tools + eu_order_tools)))  # 4
```

Without `namespace=`, each EU tool would have the same identity as its counterpart, and one
toolbox refuses two tools with one identity: give each server its own namespace (or its own
prefix). Choose the namespace once: identities are stored in the journal, so renaming it is
renaming every stored reference to the server's tools. See
[Tools](../concepts/tools.md#for-a-tools-author) for namespaces in general.

## Idempotency: what gvn sends and what the server does

MCP leaves the deduplication of `tools/call` requests to each server, so gvn hands every
server the call's key and lets it recognise a repeat. A call that ends without an answer (its `timeout` passed, or the
connection was lost) **may have run** on the server, and the failure says so. Whether it is
tried again depends on how the tool was built: with a `key_argument`, the server deduplicates a
repeat, so the failure is retryable (`tool_unavailable`); without one, it is not retried,
because the call may have taken effect, and the model is told to check before calling again.
A retryable failure is tried again only when the tools were built with
`mcp.tools(..., retry=Retry(...))`, which every tool built then declares (`Tool.retry()`).
That is safe for all of them: a tool without a `key_argument` only ever retries the unanswered
listing check (the call was never sent), and one with a `key_argument` also repeats an
unanswered call, which its server deduplicates.
When a call is delivered again, with the same key, what happens depends on the server:

| The server... | What gvn sends | A repeat with the same key |
|---|---|---|
| ignores the key | the key in `_meta` (`dev.gvn/idempotency-key`) | **may run twice** |
| reads `dev.gvn/idempotency-key` from `_meta` | the key in `_meta` | runs once when the server applies the key; the key is a gvn convention, so whether a server reads it is in its documentation, not in its listing |
| deduplicates on an argument, named in `key_argument` | the key in `_meta` and in that argument | runs once when the server applies its own promise for that argument; the model cannot choose or change the value |

gvn sends the same key for every delivery of the same call of the same run, and a different
key for every other call. Whether a repeat has an effect is the server's doing.

The key identifies one call. An agent interrupted after a tool acted and then resumed asks
its model again, and the model's next call is a new call with a new key, even when it asks
for the same thing (see [idempotency keys](../concepts/run-context.md#idempotency-keys)). For
an effect that must happen at most once whatever the run does, pass an argument built from
what it is (an order id from the run's trusted context, say), not the call's key.

!!! warning "Approval is the default for a reason"
    Because a repeat may run twice, every MCP tool needs approval by default. Clear a tool
    only when running it twice does no harm: a read, an effect that is the same however
    often it is applied, or a tool whose server deduplicates on the key you give it.

## Running it safely

gvn fixes the tool set, checks arguments, compares each tool with the catalogue before a call
and asks a person unless you cleared the tool. What you add:

- **Review the catalogue before you offer its tools.** Tool descriptions and results come from
  the server and reach the model as they are; gvn never acts on that text itself. The
  changed-tool check compares what the server *lists*, so what a tool does rests on the
  server's code: offer servers whose code you trust.
- **Treat server images like server text.** With `images=True`, gvn checks an image's format
  and size; what it shows is the server's content.
- **Clear only what is safe to repeat,** as the [section above](#idempotency-what-gvn-sends-and-what-the-server-does)
  says, and keep approval for the rest.

## Recap

- `discover` fixes what a server offers in a `Catalogue`; `tools` builds gvn tools from it,
  and a changed or dropped tool fails instead of silently becoming another one.
- An MCP tool's identity is `gvn_tools.mcp.<prefix>.<prefix>_<name>` unless the deployer
  gives the server a `namespace=`; two servers whose tools share names need different
  namespaces (or prefixes).
- `mcp.rules(order_tools, clear=[...])` takes the tools built, and matches by identity.
- Every MCP tool needs approval unless you clear it; server hints never clear anything.
- gvn checks what maps faithfully, tells the model what the server will check, and refuses
  schemas it cannot represent.
- A call cut off may have run on the server. gvn sends the call's key in `_meta`, and in an
  argument you name with `key_argument`; the server applies it.
- A server's images are described by default; `images=True` passes those that pass gvn's
  checks to the model as attachments.

**Next:** [Testing with the tools](testing.md), then the
[coding agent guide](../guides/coding-agent.md).
