---
title: "Your server functions are already MCP tools."
description: "Give a server function a tool name and list it once. An agent then calls the same schema, middleware, and handler as your form, and Farm.js keeps the defaults safe."
---


# Your server functions are already MCP tools.

KinfeMichael Tariku · Nov 2026

Your support page has a form. It calls `openTicket`, a server function that checks the email, finds the account, refuses a duplicate, and writes the ticket. Then someone wants the same thing from an agent: "open a ticket for Ada about order 123."

The usual answer is a second server. A small MCP server next to the app, with its own copy of the schema and its own idea of who may do what.

**An MCP tool should be the function your form already calls, with the same schema, the same checks, and the same error rules. Not a copy of it.**

In Farm.js that is one option on the function and one list in the config. This post shows the code, the responses an agent actually gets, and the defaults that keep the tool from becoming a second front door. Every output below comes from a production build of this code.

<span id="why-a-second-server-drifts" className="blog-heading-anchor" />

## Why a second server drifts

A hand-written MCP server starts as a copy, and copies drift.

- **The schema forks.** The form requires a valid email. The tool's schema was typed out once and still accepts any string.
- **The checks fork.** The form's middleware loads the account and refuses requests without one. The tool talks to the database directly, because that was quicker.
- **Errors leak.** I wrote a tool on the MCP TypeScript SDK's `McpServer` (1.29.0) that throws a database error. The model received the exception's message as the tool result: `connect ECONNREFUSED db-primary:5432 (user=support, password=hunter2)`.

None of these is a bug on the day you write it. They show up the day someone changes the form and forgets the tool exists.

<span id="give-the-function-a-tool-name" className="blog-heading-anchor" />

## Give the function a tool name

Here is `openTicket`, plus a query that lists open tickets. The two `mcp` options are the only lines an agent needs:

```ts
// src/features/support/server.ts
import { createServerFn, createServerMiddleware } from "@farm.js/core/server-fn";
import { createServerQuery } from "@farm.js/core/server-query";
import { z } from "zod";
import { getAccount } from "../../lib/accounts";
import { findOpenTicket, insertTicket, listOpenTickets } from "../../lib/tickets";

const withAccount = createServerMiddleware({
  async handler({ request, next }) {
    const account = request ? await getAccount(request) : null;
    if (!account) throw new Error("No account for this request");
    return next({ context: { account } });
  },
});

export const openTicket = createServerFn({
  input: z.object({ email: z.string().email(), subject: z.string().min(3) }),
  middleware: [withAccount],
  errors: {
    ALREADY_OPEN: {
      status: 409,
      message: "This customer already has an open ticket.",
      data: z.object({ id: z.string() }),
    },
  },
  mcp: { name: "open_ticket", description: "Open a support ticket for a customer." },
  async handler({ input, context, error }) {
    const open = await findOpenTicket(input.email);
    if (open) return error("ALREADY_OPEN", { id: open.id });
    return insertTicket({ ...input, openedBy: context.account.id });
  },
});

export const openTickets = createServerQuery({
  key: () => ["tickets", "open"],
  middleware: [withAccount],
  mcp: { name: "open_tickets", description: "List open support tickets." },
  handler: ({ context }) => listOpenTickets(context.account.id),
});
```

`withAccount` is ordinary middleware. `getAccount` reads the session cookie when the form calls and the bearer token when an agent does. Nothing in it knows about MCP.

Then list the two functions once and say who may call them:

```ts
// farm.config.ts
import { defineConfig } from "@farm.js/core";
import { getAgentAccount } from "./src/lib/accounts";
import { openTicket, openTickets } from "./src/features/support/server";

export default defineConfig({
  mcp: {
    name: "support",
    tools: [openTicket, openTickets],
    authorize: async ({ request }) => {
      const account = await getAgentAccount(request);
      if (!account) return false;
      return {
        subject: account.id,
        tools: account.canWrite ? ["open_ticket", "open_tickets"] : ["open_tickets"],
      };
    },
  },
});
```

That is the whole change. The app now answers MCP at `/api/mcp`:

```bash
curl http://localhost:3000/api/mcp \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"open_ticket","arguments":{"email":"ada@example.com","subject":"Refund for order 123"}}}'
```

The structured part of the result:

```json
{
  "structuredContent": {
    "result": {
      "id": "T-101",
      "email": "ada@example.com",
      "subject": "Refund for order 123",
      "openedBy": "support-agent"
    }
  }
}
```

The call ran the function's own pipeline once: the input schema, `withAccount`, the handler, and any output schema and cache invalidations. The MCP request is the function's `request`, which is why the middleware needed no second code path.

Farm.js also filled in the hints a client shows before it runs a tool. `open_tickets` is a query, so `tools/list` advertises it with `readOnlyHint: true`. `open_ticket` changes data, so it gets `destructiveHint: true` until you say otherwise. A client that asks before destructive calls will ask before this one.

<span id="what-the-agent-sees-when-a-call-fails" className="blog-heading-anchor" />

## What the agent sees when a call fails

This is where copies usually go wrong. Here are the three ways I made `open_ticket` fail, and what came back.

**A declared error.** A second ticket for the same email hits `error("ALREADY_OPEN", ...)`. The agent gets the code, the status, the public message, and the data you declared, marked as a tool error:

```json
{
  "error": {
    "code": "ALREADY_OPEN",
    "status": 409,
    "message": "This customer already has an open ticket.",
    "data": { "id": "T-101" }
  }
}
```

The model knows the call didn't succeed, and it has the ticket ID to tell the customer.

**Bad input.** An `email` of `"not-an-email"` is refused before the handler runs, with a message about the agent's own arguments, ending in `String does not match format "email"`.

**Anything else.** I made the database insert throw the same connection error as before. The agent got this:

```text
Server function failed.
```

That is the sanitized message a browser gets too. The real error went to the server log, where you can read it and the model can't:

```text
[Farm.js] MCP server function tool "open_ticket" failed: Error: connect ECONNREFUSED db-primary:5432 (user=support, password=hunter2)
```

<span id="what-an-agent-cannot-do" className="blog-heading-anchor" />

## What an agent can't do

Metadata alone publishes nothing. A function with an `mcp` option that isn't in `mcp.tools` stays a plain server function, and nothing in `mcp.tools` is reachable without `authorize`. From there:

- **No token, no tools.** When `authorize` returns `false`, the request gets a 401 with `WWW-Authenticate: Bearer`. If your tokens come from an OAuth server, [`mcp.oauth`](/docs/plugins/mcp#oauth-discovery) makes that 401 point clients at the metadata they need to sign the user in.
- **Hidden tools look like missing tools.** The read-only token above sees only `open_tickets`. When it calls `open_ticket` anyway, it gets `Tool open_ticket not found`, the same answer as `Tool delete_everything not found`. Guessing a name tells the caller nothing.
- **Oversized requests stop early.** A JSON-RPC batch of more than 25 messages gets a 400 before `authorize` runs, so one request can't multiply your session checks. Arguments with more than 10,000 array elements or object members are refused before the function runs. Both limits are [options](/docs/plugins/mcp#options).
- **Hints describe, they don't permit.** `readOnlyHint` tells a client what to expect and stops nothing. Permissions are the `tools` list that `authorize` returns. A rule like "only for this customer's own tickets" still belongs in the middleware or the handler, where it already is.

<span id="see-what-agents-did" className="blog-heading-anchor" />

## See what agents did

There are two places to look, depending on how much you want to keep.

The `mcp.tool.complete` [observability event](/docs/plugins/mcp#observe-tool-executions) fires each time a tool runs, with the tool name, `success` or `error`, and the duration. It carries no arguments, results, or credentials, so it can go to any log:

```ts
// farm.config.ts, next to mcp
observability: {
  events: ["mcp.tool.complete"],
  onEvent(event) {
    if (event.type === "mcp.tool.complete") console.log("[mcp]", event.tool, event.outcome);
  },
},
```

For the four calls above, it printed three lines:

```text
[mcp] open_ticket success
[mcp] open_ticket error
[mcp] open_ticket error
```

The bad email is missing on purpose. The MCP SDK refused those arguments before the function ran, so no tool ran.

With [Farm.js Infra analytics](/docs/infra-analytics#tool-call-payloads) on, each tool call also appears with its arguments, its result, and the [MCP client](/docs/infra-analytics#mcp-clients) that made it. Before sending, Farm.js replaces the value of any key that looks secret, such as `password` or `token`, with `[redacted]`, and leaves out anything larger than 8 KB. That check reads key names only, so a secret inside a string is sent as it is. Set `FARMJS_TOOL_PAYLOADS=off` to keep arguments and results out entirely.

<span id="limits" className="blog-heading-anchor" />

## Limits

- React Server Components apps take the same `mcp` config, but `oauth` isn't supported there yet. [Validate tokens in `authorize`](/docs/plugins/mcp#react-server-components-apps) instead.
- A page's `?actions` view tells an agent when a form posts to an API route that is also a tool. Forms bound to server functions in an RSC app aren't matched yet, so an agent reading that page won't learn that the form has a tool.

<span id="try-it" className="blog-heading-anchor" />

## Try it

```bash
pnpm add @farm.js/mcp
```

Add `mcp` to one server function, list it in `mcp.tools`, and write an `authorize` that returns `false` for anyone you don't recognize. Then point an MCP client at `/api/mcp`, or ask it what it sees:

```bash
curl http://localhost:3000/api/mcp \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```

[MCP docs](/docs/plugins/mcp#server-functions-and-queries) · [Typed server function errors](/docs/api-client#typed-server-function-errors) · [Example app](https://github.com/farming-labs/farm.js/tree/main/examples/api-mcp) · [Farm.js Infra analytics](/docs/infra-analytics)

The next time someone changes the form, the agent gets the change too. Nobody has to remember the second server, because there isn't one.
