Build your own tools

Every app comes with built-in tools, one for each of PocketBase's standard API endpoints, with names that start with pb_: pb_list_records, pb_create_record, pb_list_collections and so on. They let an agent do anything your API allows, one record at a time. Your own tools do one job each, in your app's words: "list my open tasks", "complete this task". The agent needs fewer calls and makes fewer mistakes, and your checks run on every call. When your app has tools of its own, agents are told to use them first.

A tool is a REST endpoint plus a short declaration. Every call is a request to your app's API, made as whoever signed in, so the endpoint's auth and your API rules decide what happens. There's no permission logic in the tool.

This page builds tools for a small to-do app in one TypeScript hooks file. Plain .pb.js works the same way, without the types.

Before you start

Make a tasks collection in the dashboard:

  • Fields: title (text, required), done (bool), owner (relation to users, one record, required).
  • API rules: List and View owner = @request.auth.id; Create @request.auth.id != "" && owner = @request.auth.id.

You need a user in users to try the user tools, and a superuser for the admin one.

1. Write the endpoints

Write your API as you would without MCP. Each route checks who's calling:

// pb_hooks/tasks.pb.ts
routerAdd("GET", "/api/tasks/mine", (e) => {
  const open = e.app.findRecordsByFilter("tasks", "owner = {:me} && done = false", "-created", 50, 0, { me: e.auth!.id })
  return e.json(200, open.map((r) => ({ id: r!.id, title: r!.getString("title") })))
}, $apis.requireAuth("users"))

routerAdd("POST", "/api/tasks/{id}/complete", (e) => {
  const task = e.app.findRecordById("tasks", e.request!.pathValue("id"))
  if (task.getString("owner") !== e.auth!.id) {
    throw new NotFoundError()
  }
  task.set("done", true)
  e.app.save(task)
  return e.json(200, { id: task.id, title: task.getString("title") })
}, $apis.requireAuth("users"))

routerAdd("GET", "/api/tasks/stats", (e) => {
  const open = e.app.countRecords("tasks", $dbx.hashExp({ done: false }))
  const done = e.app.countRecords("tasks", $dbx.hashExp({ done: true }))
  return e.json(200, { open, done })
}, $apis.requireSuperuserAuth())

PocketOne runs .pb.ts files directly, and writes types.d.ts and a tsconfig.json next to pb_hooks, so your editor checks $mcp calls too (TypeScript hooks).

2. Declare a tool

Below the routes, at the top level of the same file:

$mcp.addEndpoint({
  name: "tasks_list_mine",
  title: "My open tasks",
  description: "Lists your open tasks, newest first, with their ids.",
  method: "GET",
  path: "/api/tasks/mine",
  roles: ["users"],
})
  • name is <app>_<verb>_<noun>, lowercase: what the agent calls. Adding the same name again replaces the tool.
  • description is what the agent reads to decide when to use it. Say what it does and what it returns.
  • method and path are the endpoint the tool calls.
  • roles says who sees the tool. More in step 5.

The tool is read-only to the agent because it's a GET. DELETE tools are marked destructive, and everything else is marked as a write. Set annotations to say more, such as { idempotentHint: true } for a call that's safe to repeat.

3. Take arguments

Describe the arguments with a JSON Schema, and they reach the endpoint on their own:

$mcp.addEndpoint({
  name: "tasks_complete_task",
  title: "Complete a task",
  description: "Marks one of your tasks done.",
  method: "POST",
  path: "/api/tasks/{id}/complete",
  inputSchema: {
    type: "object",
    required: ["id"],
    properties: { id: { type: "string", description: "The task's id, from tasks_list_mine." } },
  },
  annotations: { idempotentHint: true },
  roles: ["users"],
})
  • A {name} in the path takes the argument of the same name, escaped.
  • Other arguments go to the query string for GET, HEAD and DELETE, and to the JSON body otherwise.
  • An argument holding a file ({ name, base64, type }, or a list of them) sends the body as a multipart upload.

Before the request is made, the arguments are checked against the schema's required properties, top-level types, enums and additionalProperties: false. A bad call comes back to the agent as an error it can read and fix.

4. Reshape the request and the result

request changes the request the tool makes. Here a tool adds tasks through PocketBase's own records API, with no route of its own, and fills in the owner from whoever is signed in:

$mcp.addEndpoint({
  name: "tasks_add_task",
  title: "Add a task",
  description: "Adds a task to your list.",
  method: "POST",
  path: "/api/collections/tasks/records",
  inputSchema: {
    type: "object",
    required: ["title"],
    properties: { title: { type: "string", description: "What to do." } },
    additionalProperties: false,
  },
  roles: ["users"],
  request: ({ args, auth, request }) => ({ ...request, body: { title: args.title, owner: auth!.id } }),
  response: ({ status, json }) => {
    if (status !== 200) {
      throw new Error(json.message)
    }
    return { id: json.id, title: json.title }
  },
})

request gets the arguments, the signed-in record (auth) and the request the tool would make. It returns a changed copy (method, path, query, body, headers, files), or nothing to keep it as it is. It can't change who the request runs as: an Authorization header it sets is dropped. Your Create rule still decides, so an agent can't add a task for someone else. additionalProperties: false turns away an owner argument before the call is made.

response decides what the agent sees. It gets status, headers, the raw body and the parsed json. Return any JSON value or a string, and throw for an error. The error's message is what the agent reads, so make it useful. In tasks_complete_task, a 404 can say what to do next:

  response: ({ status, json }) => {
    if (status === 404) {
      throw new Error("You have no task with that id. Call tasks_list_mine for the ids.")
    }
    if (status !== 200) {
      throw new Error(json.message)
    }
    return `Done: ${json.title}`
  },

Without response, a 2xx answer is the result and anything else is an error with PocketBase's message.

5. A tool for each kind of account

Superusers and your app's users are different accounts. "My open tasks" means nothing to a superuser, and task stats for the whole app aren't for users. roles lists who sees a tool, and every auth collection is a role of the same name:

$mcp.addEndpoint({
  name: "tasks_admin_stats",
  title: "Task stats",
  description: "Counts open and finished tasks across every user.",
  method: "GET",
  path: "/api/tasks/stats",
  roles: ["_superusers"],
})
Signed in as Sees
a users record tasks_list_mine, tasks_add_task, tasks_complete_task, and the built-in tools for records, files and auth
a superuser tasks_admin_stats and every built-in tool

["users", "_superusers"] is a tool for both. Leave roles out and everyone sees it. superuserOnly: true is the same as roles: ["_superusers"].

Roles only decide what's listed. A call to a tool that isn't listed for you still goes to its endpoint, so the endpoint's own check is what protects it: $apis.requireAuth("users") and $apis.requireSuperuserAuth() above. Without them, a superuser calling tasks_list_mine would get past most API rules.

6. Tell the agent how they fit together

Add a line to what agents read when they connect:

$mcp.instructions("Tasks belong to whoever is signed in. Find a task's id with tasks_list_mine before completing it.")

Try it

Restart the app, connect an MCP client (Connect an MCP client), sign in as a user and ask it to add a task and then finish it.

Or call /mcp yourself with a user's token:

TOKEN=$(curl -s -X POST http://127.0.0.1:8090/api/collections/users/auth-with-password \
  -H 'content-type: application/json' -d '{"identity":"[email protected]","password":"…"}' | jq -r .token)

curl -s -X POST http://127.0.0.1:8090/mcp -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"tasks_add_task","arguments":{"title":"Water the plants"}}}'

"method": "tools/list" shows the tools for that account. A failed call answers with "isError": true and the message the agent would read. $mcp.tools() lists every tool's name from a hook.

$mcp needs PocketOne's JS engine (the default). It isn't there with jsvm: goja.

Next