@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
158 lines (117 loc) • 10.8 kB
Markdown
---
name: mcp
description: >-
Open the app to AI assistants over MCP: softrMcpMiddleware({ actions, tools })
from /sdk, registered in src/start.ts ahead of softrAuthMiddleware,
turns the actions and defineTool tools you list into tools an assistant can
call as the signed-in visitor. defineTool runs the app's own logic, labelled
read-only or not. The list is explicit — anything left out is invisible over
MCP. The app's own login must land on toReturnPath, or the approval step
dead-ends.
metadata:
type: sub-skill
library: softr-sdk
library_version: 1.19.0
---
**Boundary.** `softrMcpMiddleware` lives on `/sdk` and is registered once, in `src/start.ts`. The actions you hand it are the same `defineQuery` / `defineMutation` values the app's own pages use — declared wherever they already live, not duplicated for MCP. The tools you hand it come from `defineTool`, also on `/sdk`, and call the same server logic the pages do. `src/start.ts` is part of the browser bundle, so a tool's handler never calls `ds` itself: it calls a helper wrapped in `createServerOnlyFn` from `/react-start` (the `record-queries` boundary).
# MCP
An app can answer an AI assistant on its own origin. The assistant signs in as an ordinary app user, and the actions and tools you list become the tools it may call. Not wired by default — a new app serves no MCP endpoint until you add the middleware.
## The URL
The app's own public origin, plus `/_softr/mcp`:
```
https://myapp.mysoftr.app/_softr/mcp
```
Custom domain, default subdomain, a staging host — whatever origin the app is published on, the path is the same. That whole string is the MCP URL. The origin on its own is the app's home page, and an assistant pointed at it gets HTML back.
## Setup
```ts
// src/start.ts
import { createCsrfMiddleware, createStart } from '@tanstack/react-start'
import { softrAuthMiddleware, softrMcpMiddleware } from '@softr/sdk'
import { listCafes } from './actions'
import { addCafe, findCafes } from './mcp-tools'
export const startInstance = createStart(() => ({
requestMiddleware: [
createCsrfMiddleware({ filter: (ctx) => ctx.handlerType === 'serverFn' }),
softrMcpMiddleware({ actions: [listCafes], tools: [findCafes, addCafe] }),
softrAuthMiddleware(),
],
}))
```
Order is part of the contract. `softrMcpMiddleware` goes **before** `softrAuthMiddleware`, and that is the only order it supports.
## Tools from the app's own logic
An action is one list, create, update or delete on one datasource. When the app does more than that — a number from a counter, an activity log entry, an email, an author stamped on the record — a tool built from the action skips it. Use `defineTool` and call the logic the app's pages already run:
```ts
// src/mcp-tools.ts
import { defineTool } from '@softr/sdk'
import { z } from 'zod'
import { createIssueFor, listIssues } from './issues'
export const createIssue = defineTool({
name: 'create_issue',
title: 'Create issue',
description: 'Create an issue in a project. Returns the new issue with its key.',
input: z.object({
projectId: z.string().describe('The project record id.'),
title: z.string().describe('A one-line summary.'),
}),
readOnly: false,
destructive: false,
handler: async (input, { user }) => createIssueFor(user, input),
})
export const findIssues = defineTool({
name: 'find_issues',
description: 'Issues in a project, newest first. Filter by status.',
input: z.object({
projectId: z.string().describe('The project record id.'),
status: z.enum(['open', 'done']).optional().describe('Only issues with this status.'),
}),
readOnly: true,
handler: async (input) => ({ issues: await listIssues(input) }),
})
```
The `ds` calls live in helpers wrapped in `createServerOnlyFn`, in a file of their own:
```ts
// src/issues.ts
import { createServerOnlyFn } from '@tanstack/react-start'
import { ds } from '@softr/sdk/server'
import { projectIssues } from './actions'
export const listIssues = createServerOnlyFn(async ({ projectId, status }: { projectId: string; status?: 'open' | 'done' }) => {
let list = ds.list(projectIssues).where((q) => q.project.isOneOf([projectId]))
if (status) list = list.where((q) => q.status.is(status))
const { records } = await list.orderBy((q) => q.createdAt.desc).limit(50)
return records.map((r) => ({ id: r.id, ...r.fields }))
})
```
`createIssueFor` is wrapped the same way.
- **`handler` runs as the signed-in user.** The `ds` calls its helpers make act as that user, with their groups, as a click in the app would. `user` is the same `User` a server function reads from `context.user`. Move logic a server function and a tool share into a function that takes the user, and pass `context.user` from the server function and `user` from the tool.
- **`handler` never calls `ds` itself.** Nor anything else from `/sdk/server`. Each such call goes in a helper wrapped in `createServerOnlyFn`, and the handler calls the helper. A helper the app's server functions already use is fine as long as it is wrapped.
- **`readOnly` is required.** `true` only when the tool changes nothing. A read-only tool that calls `ds.create`, `ds.update`, `ds.delete`, `email`, `workflow`, `upload` or an `integration` action whose method is not `GET` or `HEAD` from `/sdk/server` fails with an error, and nothing is written or sent. An integration that reads with `POST`, such as a search or GraphQL API, fails too: make that tool `readOnly: false`. So does every `auth` call that is not a plain read: a sign-in, a sign-up, a password reset, a sign-out, a profile change or an authenticator change. Your own calls to other services are not stopped, so keep them out of a read-only tool too. An `ai` call is not stopped either: it changes no data, but it spends the workspace's AI credits for an assistant approved to read only, so use it there on purpose.
- **`destructive`** says whether a tool that is not read-only deletes or overwrites data: `true` when it does, `false` when it only adds. The assistant may ask the user before it runs a destructive one. Left out, the assistant is told neither and treats the tool as one that may delete or overwrite, so set it on every tool that is not read-only.
- **`input` is a zod object.** Describe each field with `.describe()`: the assistant reads it. Use types JSON can carry: a string for a date, not `z.date()`, which fails when the tool is defined. A top-level argument the schema does not name is refused with a message saying which, and the handler does not run. Inside a nested object an unknown key is dropped without a word, so declare a nested object with `z.strictObject` to have it refused too.
- **`description` says what the tool does and when to use it.** The assistant picks tools by it.
- **Return JSON.** An object is best: the assistant gets it as structured data.
- **What the handler throws is shown to the assistant.** Throw an `Error` whose message says what went wrong in words the assistant can act on. The message of any other throw reaches it too, so catch a failed call to another service and throw your own message, not one that may carry a URL or a key.
## Choosing the tools
The list is the whole tool surface. Write it out:
- An action or tool you leave out is invisible to the assistant, even where the app's pages use it freely.
- An action you list still obeys its own `permissions`, and a tool's `ds` calls obey theirs. Listing it does not widen who may run it — the assistant runs as whoever signed in, with that user's groups.
- Anything that changes data reaches only an assistant the user allowed to make changes when they connected it. One allowed to read only sees the reads, the read-only tools and `whoami`.
- Two actions with the same `id` throw at startup, and so does a tool whose `name` is taken. So does anything that is not a `defineQuery`, `defineMutation` or `defineTool` value.
Name every tool back to the owner, saying which ones may change data.
## The login round trip
Connecting starts with an approval page the app serves. Most people hit it signed out, and that page cannot sign anyone in. It sends them to the login page named in `softr.json` (`auth.routes.login.path`), with the approval page in the search param named there (`auth.routes.login.redirectParam`).
**The app's login has to send them back.** Every exit that ends a sign-in, the second-factor step included, goes to `toReturnPath(location)` instead of the home page. See [auth/SKILL.md](../auth/SKILL.md). Lose the search param anywhere along the way and the approval dies quietly: they land on the home page, the assistant never gets its answer, nothing reports an error.
`toReturnPath` only ever goes to a path on this app. Never follow the param without it. The whole flow starts with a link someone was sent, so this is the one redirect an attacker can reliably aim.
## Failure modes
**Registering with no actions or tools.** `softrMcpMiddleware()` is valid and serves an endpoint with nothing on it. The assistant connects, lists tools, finds only `whoami`. Pass them.
**A write as an action, where the app has logic around it.** The record is written and everything the app does around it is skipped: no counter, no log entry, no email, no author. Write it as a `defineTool` that calls that logic.
**A tool handler that calls `ds` directly fails the production build.** `src/start.ts` imports the tool, so the server-only import reaches the browser bundle. The preview may still work, and publishing fails. Move the call into a `createServerOnlyFn` helper.
**Marking a tool read-only that changes data.** Its writes fail when it runs. Set `readOnly: false`.
**Registering after `softrAuthMiddleware`.** Not a supported order. Put the MCP middleware first.
**Handing over the app's URL as the MCP URL.** The origin is where the app's pages are. Without `/_softr/mcp` on the end the assistant has nothing to talk to, and the owner is left comparing a URL that looks right against a connection that never works.
**A login that drops the return target.** Sign-in works, approval doesn't. The most common break, and silent — test the connect flow signed out, not only signed in.
**Following the param without `toReturnPath`.** Anything that is not a path on this app is someone else's page, and `/\evil.test` is one of them. A prefix check misses it.
## References
- [record-queries/SKILL.md](../record-queries/SKILL.md): declaring the read actions you expose
- [record-mutations/SKILL.md](../record-mutations/SKILL.md): declaring the write actions you expose
- [current-user/SKILL.md](../current-user/SKILL.md): the `User` a tool's handler gets
- [auth/SKILL.md](../auth/SKILL.md): the sign-in and second-factor flows the round trip passes through