# Interactive MCP tools

Build MCP tools that confirm, receive files, return files, require sign-in, and finish later, with agent-ready 1.17's call state and file staging.

A tool that only reads or writes needs a handler and nothing more. This page is for the tools around it: one that confirms before it deletes, one that takes a spreadsheet, one that returns a report, and the sign-in that protects them all. The examples use `agent-ready` 1.17 or newer. Run `ferrite add agent-ready` to install it, and see [Packages](/developers/packages/) to update an existing copy.

Each example is a method on the `PageSource` your application already implements. `self.ctx` is the application's `AppContext`, and `self.owner` is the caller taken from the authenticated request.

## Confirm once, on every instance

`confirm` asks the person before a tool runs. It seals the question to the tool, the exact arguments and the caller, keeps the sealing key and the record of used confirmations in a store binding, and returns `None` when the tool may run:

```rust filename="src/agent.rs"
use crate::agent_ready::confirm::{self, Proof};

async fn mcp_tool_call_mrtr(
    &self,
    name: String,
    params: Value,
) -> Option<Result<Value, ElicitationError>> {
    match name.as_str() {
        "delete_note" => {
            confirm::confirm(
                self.ctx, "data", &self.owner, &name, &params,
                "Delete this note?", Proof::Tick,
            )
            .await
        }
        "delete_notebook" => {
            confirm::confirm(
                self.ctx, "data", &self.owner, &name, &params,
                "Delete the notebook and every note in it?", Proof::Type("delete everything"),
            )
            .await
        }
        "import_note" => Some(self.import_note(&params).await),
        _ => None,
    }
}
```

`Proof::Tick` shows one box to tick. `Proof::Type` asks for exact text, for an act that cannot be undone. Check that the caller may run the tool before you ask. A client that cannot show a form reaches the handler as before, so keep the handler's own rules, such as an explicit `confirm` argument or a link to the page where a person does the same thing.

For a password, a key or a payment, ask with `elicitation::url_request(message, url)` and have the page at that URL check that the person signed in there is the one who made the call. `mcp_request_mrtr` asks the same way during `prompts/get` and `resources/read`.

## Describe what a tool does

`mcp_tool_hints` adds the title and annotations a client shows before it runs a tool:

```rust filename="src/agent.rs"
fn mcp_tool_hints(&self) -> Vec<ToolHints> {
    vec![ToolHints::new("delete_note").title("Delete a note").destructive(true)]
}
```

`.open_world(true)` says the tool reaches systems outside your application, `.icon(...)` adds an icon, and `.app_only()` keeps a tool for your own [view](/developers/mcp-apps/) and out of the model's list. Arguments are checked against the declared input schema before your handler runs, and a violation comes back as `isError: true` so the model can correct the call.

## Receive a file

`StagedFiles` issues an upload target on your own `/mcp` endpoint, receives the one `PUT`, and confirms the bytes when the client repeats the call. It keeps its records in a store and the bytes in a blob service, and removes both after they expire.

```rust filename="src/agent.rs"
fn mcp_files_config(&self) -> FilesConfig {
    FilesConfig {
        upload: true,
        max_inline_bytes: Some(files::DEFAULT_MAX_INLINE_BYTES),
        download: true,
    }
}

fn staged(&self) -> StagedFiles<'_> {
    StagedFiles::new(self.ctx, "data", "files")
}

async fn mcp_file_http(
    &self,
    method: &str,
    subpath: &str,
    headers: &[(String, String)],
    body: &[u8],
) -> Option<AnswerH> {
    self.staged().http(Some(&self.owner), method, subpath, headers, body).await
}
```

The tool takes a small file inline and asks for a larger one:

```rust filename="src/agent.rs"
async fn import_note(&self, params: &Value) -> Result<Value, ElicitationError> {
    let args = params.get("arguments").cloned().unwrap_or_else(|| json!({}));
    let files = match files::parse_file_arguments(
        &args, &["file"], Some(MAX_UPLOAD_BYTES), files::DEFAULT_MAX_INLINE_BYTES, false,
    ) {
        Ok(files) if !files.is_empty() => files,
        Ok(_) => return Ok(files::file_error_result("Choose a file.")),
        Err(reason) => return Ok(files::file_error_result(reason)),
    };
    let file = &files[0];
    if let Some(bytes) = &file.inline_bytes {
        return Ok(self.save_note(bytes).await);
    }
    let now = self.ctx.now_ms();
    let secret = confirm::key(self.ctx, "data").await.map_err(ElicitationError::internal)?;
    let used = StoreSingleUse { ctx: self.ctx, store: "data", prefix: "" };
    if let Some(state) =
        CallState::from_retry(&secret, params, "import_note", &self.owner, now, &used).await?
    {
        if state.phase != Phase::Upload {
            return Err(ElicitationError::invalid_params("requestState is not from an upload request"));
        }
        let slot = state.slots.get(&file.id).and_then(Value::as_str).unwrap_or_default();
        let bytes = match self.staged().confirm(Some(&self.owner), slot, file).await {
            Ok(bytes) => bytes,
            Err(reason) => return Ok(files::file_error_result(reason)),
        };
        state.consume(&used).await?;
        return Ok(self.save_note(&bytes).await);
    }
    let expires = now + files::UPLOAD_STATE_TTL_MS;
    let mut state = CallState::new("import_note", &args, &self.owner, &self.nonce()?, expires);
    let (target, slot) = self
        .staged()
        .issue(Some(&self.owner), file, expires)
        .await
        .map_err(ElicitationError::internal)?;
    state.slots.insert(file.id.clone(), json!(slot));
    files::upload_required(&secret, params, &state, &files, &[target])
}

fn nonce(&self) -> Result<String, ElicitationError> {
    crate::crypto::random_token(16).map_err(|e| ElicitationError::internal(e.to_string()))
}
```

Declare the store, the blob service, and a route that forwards `authorization` and `range`:

```json filename="ferrite.json"
{
  "services": [
    { "name": "requests", "primitive": "queue" },
    { "name": "data", "primitive": "store" },
    { "name": "files", "primitive": "blob" }
  ],
  "applications": [{
    "name": "notes",
    "artifact_key": "apps/notes@v1",
    "artifact_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "bindings": [
      { "handle": "requests", "kind": "queue", "service": "requests" },
      { "handle": "data", "kind": "store", "service": "data" },
      { "handle": "files", "kind": "blob", "service": "files" }
    ],
    "routes": [{
      "prefix": "/mcp",
      "binding": "requests",
      "kind": "api",
      "forward_headers": ["mcp-protocol-version", "mcp-method", "mcp-name", "origin", "accept", "authorization", "range"]
    }]
  }]
}
```

`from_retry` refuses a forged, expired or used `requestState`, and answers that arrive without one. Confirm the bytes before `consume`, so a retry that comes too early does not spend the state. The target, the stored bytes and the `requestState` share one expiry, so a client may upload early and repeat the call late. One staged file holds at most 262,144 bytes, the request size of a route; [an upload route](#take-files-up-to-64-mib) takes larger ones. A file tool is listed only to clients that declare the extension, so keep another way in, such as an upload page, for everyone else.

### Take files up to 64 MiB

Add an [upload route](/developers/large-uploads/) under the MCP address, and forward the same headers to it through the `api` route:

```json
{ "prefix": "/mcp/files/upload/", "binding": "files", "kind": "upload", "key_prefix": "uploads/" }
```

This takes `agent-ready` 1.18. Give the staging that prefix, a reader of what the route stores, and the request being answered, which your `PageSource` keeps as `self.req` beside `self.ctx` and `self.owner`. Here the `PageSource` is called `Agent`, and this `staged` replaces the one above:

```rust filename="src/agent.rs"
use ferrite_app::{large_object, AppContext, IngressRequest};
use crate::agent_ready::uploads::{RouteUploads, StagedFiles, UploadObjects};

struct Agent<'a> {
    ctx: &'a AppContext,
    req: &'a IngressRequest,
    owner: String,
}

struct Uploaded<'a>(&'a AppContext);

impl UploadObjects for Uploaded<'_> {
    async fn read(&self, key: &str) -> Result<Option<Vec<u8>>, String> {
        let mut blob = self.0.blob("files").map_err(|e| e.to_string())?;
        large_object::get(&mut blob, key.as_bytes()).await.map_err(|e| e.to_string())
    }
    async fn remove(&self, key: &str) -> Result<(), String> {
        let mut blob = self.0.blob("files").map_err(|e| e.to_string())?;
        large_object::delete(&mut blob, key.as_bytes()).await.map(|_| ()).map_err(|e| e.to_string())
    }
}

impl Agent<'_> {
    fn staged(&self) -> RouteUploads<'_, Uploaded<'_>> {
        StagedFiles::new(self.ctx, "data", "files")
            .with_upload_route("uploads/", Uploaded(self.ctx))
            .for_request(&self.req.idempotency_key)
    }
}
```

The rest of the tool stays as it is, with `uploads::MAX_ROUTE_UPLOAD_BYTES`, or a limit of your own below it, as the size you declare and parse. The gateway asks `mcp_file_http` before it reads a byte, so a target that is used, expired, or issued to someone else is refused without a transfer, and the stored file's digest is checked against the one the client declared. `confirm_stored` returns the key instead of the bytes, for a tool that reads a large file in chunks.

## Return a file

`publish` stores the bytes and returns a target that serves them, with byte ranges, until it expires:

```rust filename="src/agent.rs"
async fn export_notes(&self, csv: &[u8]) -> Result<ToolOutcome, String> {
    let expires = self.ctx.now_ms() + 3_600_000;
    let target = self
        .staged()
        .publish(Some(&self.owner), "notes.csv", "text/csv", csv, expires)
        .await?;
    Ok(ToolOutcome::ok(json!({"file": "notes.csv", "bytes": csv.len()})).with_downloads(&[target]))
}
```

Describe the file in the result too, as here, because the face removes download targets from a call that did not declare them.

## Load skills from files

`Skill::embedded` reads the front matter from `SKILL.md` itself, so the entry and the file always agree, and reports every rule a skill breaks:

```rust filename="src/agent.rs"
fn skills(&self) -> Vec<Skill> {
    let returns = Skill::embedded("skill://shop/returns", &[
        ("SKILL.md", "text/markdown", include_bytes!("skills/returns/SKILL.md").as_slice()),
    ]);
    returns.and_then(|skill| skills::catalog(vec![skill])).unwrap_or_default()
}
```

Assert in a test that the catalog is not empty.

## Let a view reach the network

`mcp_ui_meta` declares the origins an [MCP App](/developers/mcp-apps/) page may use. The host builds the page's content security policy from it:

```rust filename="src/agent.rs"
fn mcp_ui_meta(&self) -> Vec<UiMeta> {
    vec![UiMeta {
        connect_domains: vec!["https://maps.example".into()],
        ..UiMeta::new("ui://shop/board.html")
    }]
}
```

## Require sign-in

`mcp_auth` names the authorization server that issues tokens for your endpoint, and `mcp_authorize` decides each request. The face serves the protected-resource metadata and turns the verdict into the `401` and `403` challenges that start a client's sign-in.

```rust filename="src/agent.rs"
fn mcp_auth(&self) -> Option<McpAuth> {
    Some(McpAuth::new("https://issuer.example").with_scopes(&["notes:read"]))
}

async fn mcp_authorize(&self, request: McpRequest<'_>) -> McpAccess {
    match self.verify(request.bearer).await {
        Some(scopes) if scopes.iter().any(|s| s == "notes:read") => McpAccess::Allow,
        Some(_) => McpAccess::InsufficientScope(vec!["notes:read".into()]),
        None => McpAccess::Unauthorized,
    }
}
```

Your `verify` checks the signature or introspects the token, its expiry, and that its audience is this application's `/mcp` address. [Per-app OAuth](/developers/poppy-oauth/) can be the issuer, and [Enterprise-managed authorization](/developers/enterprise-managed-authorization/) lets a customer's identity provider grant access for its members.

## Keep tasks in a store

`AppTaskStore::new(&ctx, "data")` is a `TaskStore` over a store binding, for the [task host](/developers/mcp-tasks/#add-tasks-to-your-own-app). It bounds the tasks each caller keeps, and a finished result stays readable for at least an hour. Name a tool in `task_sync_fallback` when it can also finish within one request, for a client without Tasks. A tool that needs a confirmation or a file asks for it through `mcp_tool_call_mrtr`, before its task exists.
