capable-kit 0.0.1-alpha.3 → 0.0.1-alpha.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +21 -3
  2. package/dist/ai-sdk.d.mts +2 -2
  3. package/dist/ai-sdk.mjs +1 -1
  4. package/dist/app.d.mts +1 -1
  5. package/dist/app.mjs +1 -1
  6. package/dist/bin.mjs +17 -16
  7. package/dist/bin.mjs.map +1 -1
  8. package/dist/cli.d.mts +1 -1
  9. package/dist/cli.mjs +1 -1
  10. package/dist/core.d.mts +3 -3
  11. package/dist/core.mjs +2 -2
  12. package/dist/eve.d.mts +1 -1
  13. package/dist/eve.mjs +1 -1
  14. package/dist/http.d.mts +1 -1
  15. package/dist/http.mjs +1 -1
  16. package/dist/{index-BB5ogMv-.d.mts → index-Be8-UVBC.d.mts} +49 -8
  17. package/dist/{index-B2ru1zGQ.d.mts → index-D2CRRUzH.d.mts} +6 -6
  18. package/dist/{index-B_I9n6gN.d.mts → index-Dbc4g9WM.d.mts} +4 -3
  19. package/dist/{index-AqKbVZ8Z.d.mts → index-DwXlaTXI.d.mts} +4 -4
  20. package/dist/index.d.mts +4 -4
  21. package/dist/index.mjs +3 -3
  22. package/dist/mcp.d.mts +2 -2
  23. package/dist/mcp.mjs +1 -1
  24. package/dist/{mount--YHrgRHJ.mjs → mount-xvMsjz1B.mjs} +65 -27
  25. package/dist/mount-xvMsjz1B.mjs.map +1 -0
  26. package/dist/runtime-support.d.mts +1 -1
  27. package/dist/runtime-support.mjs +6 -6
  28. package/dist/runtime-support.mjs.map +1 -1
  29. package/dist/server.d.mts +2 -2
  30. package/dist/server.mjs +2 -2
  31. package/dist/{src-DX2xrplP.mjs → src-BF70JLxI.mjs} +24 -13
  32. package/dist/src-BF70JLxI.mjs.map +1 -0
  33. package/dist/{src-3UaBqI8H.mjs → src-C2MGIlT0.mjs} +17 -18
  34. package/dist/src-C2MGIlT0.mjs.map +1 -0
  35. package/dist/{src-DtSY5fzY.mjs → src-CDxL6w3d.mjs} +7 -7
  36. package/dist/{src-DtSY5fzY.mjs.map → src-CDxL6w3d.mjs.map} +1 -1
  37. package/dist/{src-BjBxOv7x.mjs → src-Db6-XSnU.mjs} +20 -12
  38. package/dist/src-Db6-XSnU.mjs.map +1 -0
  39. package/dist/{src-B53ZbNtC.mjs → src-DdV82An-.mjs} +137 -3
  40. package/dist/src-DdV82An-.mjs.map +1 -0
  41. package/dist/{subscription-McaLyHM2.d.mts → subscription-Bq792Ad2.d.mts} +2 -2
  42. package/docs/CONTEXT.md +113 -0
  43. package/docs/README.md +28 -0
  44. package/docs/internal/README.md +16 -0
  45. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +24 -0
  46. package/docs/internal/architecture.md +134 -0
  47. package/docs/internal/capability-first-model.md +160 -0
  48. package/docs/internal/implementation-friction.md +705 -0
  49. package/docs/internal/why-capable.md +94 -0
  50. package/docs/site/capable-orpc-and-trpc.mdx +133 -0
  51. package/docs/site/concepts/apps.mdx +217 -0
  52. package/docs/site/concepts/architecture.mdx +83 -0
  53. package/docs/site/concepts/capabilities.mdx +249 -0
  54. package/docs/site/concepts/errors.mdx +93 -0
  55. package/docs/site/concepts/presentations.mdx +161 -0
  56. package/docs/site/hosting/any-fetch-host.mdx +74 -0
  57. package/docs/site/hosting/next-js.mdx +77 -0
  58. package/docs/site/hosting/standalone-server.mdx +94 -0
  59. package/docs/site/introduction.mdx +259 -0
  60. package/docs/site/patterns/composition.mdx +142 -0
  61. package/docs/site/patterns/remote-apps.mdx +117 -0
  62. package/docs/site/patterns/subscriptions.mdx +87 -0
  63. package/docs/site/quickstart.mdx +386 -0
  64. package/docs/site/reference/packages-and-entry-points.mdx +72 -0
  65. package/docs/site/reference/surface-metadata.mdx +84 -0
  66. package/docs/site/reference/the-cap-cli.mdx +81 -0
  67. package/docs/site/surfaces/ai-sdk.mdx +94 -0
  68. package/docs/site/surfaces/cli.mdx +138 -0
  69. package/docs/site/surfaces/eve.mdx +121 -0
  70. package/docs/site/surfaces/http-and-openapi.mdx +111 -0
  71. package/docs/site/surfaces/mcp.mdx +110 -0
  72. package/docs/site/surfaces/react-query.mdx +80 -0
  73. package/docs/site/surfaces/typescript.mdx +123 -0
  74. package/docs/site/surfaces.mdx +78 -0
  75. package/docs/site/why-capable.mdx +99 -0
  76. package/package.json +13 -3
  77. package/src/index.test.ts +1 -0
  78. package/src/index.ts +5 -1
  79. package/src/package.test.ts +102 -0
  80. package/dist/mount--YHrgRHJ.mjs.map +0 -1
  81. package/dist/src-3UaBqI8H.mjs.map +0 -1
  82. package/dist/src-B53ZbNtC.mjs.map +0 -1
  83. package/dist/src-BjBxOv7x.mjs.map +0 -1
  84. package/dist/src-DX2xrplP.mjs.map +0 -1
@@ -0,0 +1,249 @@
1
+ ---
2
+ title: "Capabilities"
3
+ description: "A capability is one typed capability: input, output, errors, middleware, and a handler."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/concepts/capabilities", frontmatter);
9
+
10
+ <DocsPage href="/concepts/capabilities" frontmatter={frontmatter}>
11
+
12
+ A capability is the only place where behaviour is defined. Everything else in Capable — apps, servers, CLIs, tools — reads capabilities and presents them. Start with the behaviour, then add contracts and presentation details only when they become useful.
13
+
14
+ ## Start with the minimum [#minimal]
15
+
16
+ ```ts title="capabilities.ts"
17
+ import { capability } from "capable-kit";
18
+
19
+ export const ping = capability({
20
+ id: "system.ping",
21
+ handler: () => "pong",
22
+ });
23
+ ```
24
+
25
+ This is a complete capability. The `id` is its stable execution identity; the `handler` is the behaviour. Nothing else is required.
26
+
27
+ TypeScript infers that calling it returns a string. Because it takes no input and needs no context, there is nothing else to declare.
28
+
29
+ From here on, each example keeps familiar scaffolding dimmed and marks the concept introduced in that step with a solid rule.
30
+
31
+ ## Validate input and output [#contracts]
32
+
33
+ Add an `input` schema when callers provide values. Capable parses it once before the handler runs, so the handler receives validated, typed input on every surface.
34
+
35
+ ```ts title="capabilities.ts" highlight="2,11-12"
36
+ import { capability } from "capable-kit";
37
+ import { z } from "zod";
38
+
39
+ const Todo = z.object({
40
+ id: z.string(),
41
+ title: z.string(),
42
+ });
43
+
44
+ export const createTodo = capability({
45
+ id: "todos.create",
46
+ input: z.object({ title: z.string().min(1) }),
47
+ output: Todo,
48
+ handler: ({ input }) => ({ id: "1", title: input.title }),
49
+ });
50
+ ```
51
+
52
+ The `output` schema is optional: TypeScript can infer the return type from the handler. Declare it when you also need runtime output validation and a portable JSON Schema for OpenAPI and agent tools.
53
+
54
+ ## Describe what it does [#intent]
55
+
56
+ Titles and descriptions help people and agents discover the capability. They become CLI help, OpenAPI descriptions, and tool descriptions; they never change execution.
57
+
58
+ ```ts title="capabilities.ts" highlight="3-5"
59
+ export const listTodos = capability({
60
+ id: "todos.list",
61
+ title: "List todos",
62
+ description: "List every todo owned by the current user.",
63
+ effect: "read",
64
+ handler: () => todos.list(),
65
+ });
66
+ ```
67
+
68
+ `effect` describes intent shared by every surface. It is separate from presentation metadata because a read stays a read whether it is called through HTTP, a CLI, or an agent.
69
+
70
+ | Effect | What surfaces may derive |
71
+ | --- | --- |
72
+ | `read` | GET defaults and read-only agent hints. |
73
+ | `write` | A state-changing operation and POST defaults. |
74
+ | `destructive` | POST defaults and destructive-operation safety hints. |
75
+
76
+ Omit `effect` when the intent is genuinely unknown. See [the complete surface mapping](/reference/metadata#effect).
77
+
78
+ ## Give the handler context [#context]
79
+
80
+ Context contains dependencies supplied by the runtime: stores, sessions, loggers, or other apps. A capability declares the shape it needs but never constructs those values.
81
+
82
+ ```ts title="capabilities.ts" highlight="1-4,6,10"
83
+ type TodoContext = {
84
+ todos: TodoStore;
85
+ userId: string;
86
+ };
87
+
88
+ const todoCapability = capability.withContext<TodoContext>();
89
+
90
+ export const listTodos = todoCapability({
91
+ id: "todos.list",
92
+ handler: ({ context }) => context.todos.list(context.userId),
93
+ });
94
+ ```
95
+
96
+ `withContext()` returns a capability factory, not a special kind of capability. Give the factory a domain name such as `todoCapability`, then use it to define named capabilities before composing an app. The context provider is added later by `createApp()` or a server.
97
+
98
+ ## Declare expected failures [#errors]
99
+
100
+ Declared errors are part of the contract. They keep the same code, status, and typed data for local and remote callers, while unexpected exceptions become `INTERNAL_SERVER_ERROR`.
101
+
102
+ ```ts title="capabilities.ts" highlight="1-3,8-11"
103
+ const TodoErrors = defineErrors({
104
+ NOT_FOUND: { status: 404, message: "Todo not found" },
105
+ });
106
+
107
+ export const getTodo = todoCapability({
108
+ id: "todos.get",
109
+ input: z.object({ todoId: z.string() }),
110
+ errors: TodoErrors,
111
+ handler: async ({ input, context }) => {
112
+ const todo = await context.todos.get(input.todoId);
113
+ if (!todo) throw TodoErrors.NOT_FOUND();
114
+ return todo;
115
+ },
116
+ });
117
+ ```
118
+
119
+ Only attach failures a caller can reasonably handle. Error sets and typed catching are covered in depth on the [Errors page](/concepts/errors).
120
+
121
+ ## Wrap shared behaviour with middleware [#middleware]
122
+
123
+ Middleware runs around the handler. It is useful for semantic policy that must hold no matter which surface calls the capability: authorization, tracing, transactions, or domain-level rate limits.
124
+
125
+ ```ts title="middleware.ts" highlight="1-10,14"
126
+ const logDuration: CapabilityMiddleware<TodoContext> = async ({
127
+ next,
128
+ }) => {
129
+ const startedAt = performance.now();
130
+ try {
131
+ return await next();
132
+ } finally {
133
+ console.info(`todos.list took ${performance.now() - startedAt}ms`);
134
+ }
135
+ };
136
+
137
+ export const listTodos = todoCapability({
138
+ id: "todos.list",
139
+ middleware: [logDuration],
140
+ handler: ({ context }) => context.todos.list(context.userId),
141
+ });
142
+ ```
143
+
144
+ > Middleware is semantic, not transport-level. It cannot see requests or headers, which is what lets it behave identically for a local call, an HTTP request, a CLI command, and a tool call. Put request-level concerns in the server instead.
145
+
146
+ Put middleware on a `group()` when several capabilities in one branch share the policy and the rest of the app does not.
147
+
148
+ ## Describe each surface with metadata [#metadata]
149
+
150
+ App paths give every surface enough information to derive routes, commands, and tool names. Add `meta` when a surface needs details that the capability itself cannot express.
151
+
152
+ ```ts title="capabilities.ts" highlight="4-7"
153
+ export const getTodo = todoCapability({
154
+ id: "todos.get",
155
+ input: z.object({ todoId: z.string() }),
156
+ meta: {
157
+ http: { method: "GET", route: "/todos/:todoId" },
158
+ cli: { positional: ["todoId"] },
159
+ },
160
+ handler: ({ input, context }) => context.todos.get(input.todoId),
161
+ });
162
+ ```
163
+
164
+ Here the HTTP metadata describes a resource-shaped route, while the CLI metadata says that `todoId` is positional. The handler does not see these presentation details, and other surfaces ignore keys they do not own. See [Surface metadata](/reference/metadata) for every supported key.
165
+
166
+ ## Add a presentation [#presentation]
167
+
168
+ A capability always returns one canonical structured value. `toPresentation` can derive an optional human-readable view without changing that contract. Returning a string is the smallest form and is treated as Markdown.
169
+
170
+ ```ts title="capabilities.ts" highlight="1,6-9"
171
+ import { md } from "capable-kit";
172
+
173
+ export const listTodos = todoCapability({
174
+ id: "todos.list",
175
+ handler: ({ context }) => context.todos.list(context.userId),
176
+ toPresentation: (todos) =>
177
+ todos.length === 0
178
+ ? "No todos."
179
+ : todos.map((todo) => md`- **${todo.title}**`).join("\n"),
180
+ });
181
+ ```
182
+
183
+ Only surfaces that need a presentation ask the runtime to produce it. The CLI renders this Markdown in the terminal, MCP gives it to agents as tool text, and HTTP requests it when the caller accepts `text/markdown`. Typed calls and `--json` still receive only the original array. For tables, images, and downloadable files, see [Presentations](/concepts/presentations).
184
+
185
+ ## How execution fits together [#lifecycle]
186
+
187
+ Once these pieces are present, every caller enters the same lifecycle. A surface only translates its own transport into an input object.
188
+
189
+ 1. **Parse input.** The input schema runs once.
190
+ 2. **Run middleware.** Group middleware runs outermost, then capability middleware, in declaration order.
191
+ 3. **Run the handler.** It receives `{ input, context, signal }`.
192
+ 4. **Normalize errors.** Declared errors keep their contract; unexpected failures become `INTERNAL_SERVER_ERROR`.
193
+ 5. **Validate output.** The optional output schema runs before the canonical result is returned.
194
+
195
+ ## Running a capability directly [#direct]
196
+
197
+ A capability is executable on its own. Use `executeCapability()` in tests, scripts, or jobs where an app tree adds nothing.
198
+
199
+ ```ts title="job.ts"
200
+ import { executeCapability } from "capable-kit";
201
+
202
+ const todo = await executeCapability(getTodo, {
203
+ input: { todoId: "t_123" },
204
+ context: { todos, userId },
205
+ signal,
206
+ });
207
+ ```
208
+
209
+ Direct execution applies the capability's own validation, middleware, and declared errors. Middleware and errors contributed by a group only exist when the capability is executed through the app tree that contains it.
210
+
211
+ ## Put it all together [#complete]
212
+
213
+ A capability can grow into the full declaration below, but only as each concern becomes real. The handler remains the centre; every other field either strengthens its contract, shares semantic policy, or helps a surface present it.
214
+
215
+ Subscriptions are the remaining optional execution mode. A read capability can add `subscribe` beside its handler when it needs to emit replacement snapshots; see [Subscriptions](/patterns/subscriptions).
216
+
217
+ ```ts title="capabilities.ts"
218
+ import { capability, defineErrors, md } from "capable-kit";
219
+ import { z } from "zod";
220
+
221
+ const TodoErrors = defineErrors({
222
+ NOT_FOUND: { status: 404, message: "Todo not found" },
223
+ });
224
+
225
+ const todoCapability = capability.withContext<TodoContext>();
226
+
227
+ export const getTodo = todoCapability({
228
+ id: "todos.get",
229
+ title: "Get a todo",
230
+ description: "Read one todo owned by the current user.",
231
+ effect: "read",
232
+ input: z.object({ todoId: z.string() }),
233
+ output: Todo,
234
+ errors: TodoErrors,
235
+ middleware: [requireUser],
236
+ meta: {
237
+ http: { method: "GET", route: "/todos/:todoId" },
238
+ cli: { positional: ["todoId"] },
239
+ },
240
+ handler: async ({ input, context }) => {
241
+ const found = await context.todos.get(input.todoId);
242
+ if (!found) throw TodoErrors.NOT_FOUND();
243
+ return found;
244
+ },
245
+ toPresentation: (todo) => md`- **${todo.title}**`,
246
+ });
247
+ ```
248
+
249
+ </DocsPage>
@@ -0,0 +1,93 @@
1
+ ---
2
+ title: "Errors"
3
+ description: "Declare the failures a caller should handle, and let everything else be an internal error."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/concepts/errors", frontmatter);
9
+
10
+ <DocsPage href="/concepts/errors" frontmatter={frontmatter}>
11
+
12
+ An error set is a contract. Its members are callable factories that construct a typed error, and type guards that narrow it after a local or remote call — so the caller sees the same failures the handler declared.
13
+
14
+ ## Declare the error set [#define]
15
+
16
+ ```ts title="errors.ts"
17
+ import { defineErrors } from "capable-kit";
18
+ import { z } from "zod";
19
+
20
+ export const TodoErrors = defineErrors({
21
+ NOT_FOUND: {
22
+ status: 404,
23
+ message: "Todo not found",
24
+ data: z.object({ todoId: z.string() }),
25
+ },
26
+ LIMIT_REACHED: {
27
+ status: 409,
28
+ message: "This workspace reached its todo limit",
29
+ },
30
+ });
31
+ ```
32
+
33
+ | Key | Meaning |
34
+ | --- | --- |
35
+ | `status` | HTTP status used when this error crosses an HTTP boundary. |
36
+ | `message` | Default message. Always replaces the thrown message. |
37
+ | `data` | Optional schema for structured payload, validated on throw. |
38
+
39
+ ## Throw and catch [#throw]
40
+
41
+ Attach the set to a capability with `errors`, then throw its members. Only declared errors survive; everything else is treated as a bug.
42
+
43
+ ```ts title="capabilities.ts"
44
+ const deleteTodo = todo({
45
+ id: "todos.delete",
46
+ effect: "destructive",
47
+ input: z.object({ todoId: z.string() }),
48
+ errors: TodoErrors,
49
+ handler: async ({ input, context }) => {
50
+ const deleted = await context.todos.delete(input.todoId);
51
+ if (!deleted) throw TodoErrors.NOT_FOUND({ todoId: input.todoId });
52
+ return { deleted: true as const };
53
+ },
54
+ });
55
+ ```
56
+
57
+ ```ts title="caller.ts"
58
+ try {
59
+ await app.todos.delete({ todoId });
60
+ } catch (error) {
61
+ if (TodoErrors.NOT_FOUND.is(error)) {
62
+ console.error(error.data.todoId); // typed
63
+ return;
64
+ }
65
+ throw error;
66
+ }
67
+ ```
68
+
69
+ The same guard works against a remote app, because the error code and data cross the Capable transport intact.
70
+
71
+ ## Undeclared failures [#undeclared]
72
+
73
+ Any failure that is not in the located capability's error sets becomes `INTERNAL_SERVER_ERROR`. The original value is kept as `cause` on the server and is never serialized to a caller.
74
+
75
+ > **Why the strictness**
76
+ >
77
+ > A surface can only present failures it can describe. Declared errors appear in OpenAPI, in CLI output, and in agent-visible schemas. Leaking arbitrary exception text would make those contracts unreliable and would risk exposing internals.
78
+
79
+ ## Inherited errors [#groups]
80
+
81
+ A group can contribute an error set to every capability beneath it, which is the usual place for cross-cutting failures such as authentication.
82
+
83
+ ```ts title="capable.app.ts"
84
+ const todos = group({
85
+ errors: AuthErrors,
86
+ middleware: [requireUser],
87
+ capabilities: { list, create, delete: deleteTodo },
88
+ });
89
+ ```
90
+
91
+ A group and a capability may not declare the same error code twice. The conflict is reported when the app definition is created, not at call time.
92
+
93
+ </DocsPage>
@@ -0,0 +1,161 @@
1
+ ---
2
+ title: "Presentations"
3
+ description: "Derive portable Markdown, tables, images, and files from canonical output."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/concepts/presentations", frontmatter);
9
+
10
+ <DocsPage href="/concepts/presentations" frontmatter={frontmatter}>
11
+
12
+ A capability returns one canonical output. `toPresentation` derives a meaningful representation of that data without turning the representation into the API contract. The same Presentation helps a person understand a result in the CLI and gives an agent a focused, often more token-efficient account of what happened.
13
+
14
+ ## Why present canonical output? [#purpose]
15
+
16
+ Canonical output is designed for programs: it is complete, stable, and structured. That does not mean its raw JSON is the best explanation of a result. It may repeat field names hundreds of times, expose internal bookkeeping, or leave important values without useful labels.
17
+
18
+ A Presentation lets the capability author select what matters, name it clearly, and put it in a useful order. Humans get readable headings, tables, images, and file links. Agents get concise text and structured visual resources instead of having to infer the meaning of an entire JSON object. The canonical output remains available whenever exact machine-readable data is needed.
19
+
20
+ ## Start with Markdown [#markdown]
21
+
22
+ Return a string when Markdown is enough. Existing string renderers stay small and need no wrapper.
23
+
24
+ ```ts title="capabilities.ts"
25
+ import { capability, md } from "capable-kit";
26
+
27
+ export const getWeather = capability({
28
+ id: "weather.get",
29
+ handler: () => ({ city: "Vienna", temperature: 24 }),
30
+ toPresentation: (weather) =>
31
+ md`**${weather.city}:** ${weather.temperature}°C`,
32
+ });
33
+ ```
34
+
35
+ Typed calls still receive `{ city, temperature }`. The string is only produced when a presentation-aware surface asks for it.
36
+
37
+ ## Compose richer output [#parts]
38
+
39
+ `toPresentation` may also return one part or an ordered array of strings and parts. Import the builders from the same root entry point:
40
+
41
+ ```ts title="capabilities.ts"
42
+ import { capability, md, present } from "capable-kit";
43
+
44
+ export const createReport = capability({
45
+ id: "reports.create",
46
+ handler: () => buildReport(),
47
+ toPresentation: (report) => [
48
+ md`## ${report.title}`,
49
+ present.table({
50
+ caption: "Daily totals",
51
+ columns: ["Date", "Requests", "Errors"],
52
+ rows: report.days.map((day) => [
53
+ day.date,
54
+ day.requests,
55
+ day.errors,
56
+ ]),
57
+ }),
58
+ present.image({
59
+ base64: report.chartBase64,
60
+ mimeType: "image/png",
61
+ alt: "Requests and errors over time",
62
+ }),
63
+ present.file({
64
+ url: report.csvUrl,
65
+ name: "daily-totals.csv",
66
+ mimeType: "text/csv",
67
+ size: report.csvSize,
68
+ description: "The underlying report data",
69
+ }),
70
+ ],
71
+ });
72
+ ```
73
+
74
+ The array order is meaningful. A surface can render a heading, then a table, then an image and a file link in that sequence.
75
+
76
+ ## What the CLI shows [#cli]
77
+
78
+ The CLI uses the general Markdown representation and adds terminal styling. The report above reads approximately like this:
79
+
80
+ ```text title="terminal"
81
+ $ cap cli reports create
82
+
83
+ API traffic
84
+
85
+ Daily totals
86
+
87
+ Date Requests Errors
88
+ 2026-07-30 18,420 31
89
+ 2026-07-31 19,105 22
90
+
91
+ [Image: Requests and errors over time]
92
+
93
+ daily-totals.csv — The underlying report data — text/csv, 42.3 kB
94
+ ```
95
+
96
+ Running the same command with `--json` skips `toPresentation` entirely and prints the canonical report object. An MCP client can instead keep the heading and table as text while receiving the chart and file as native content blocks.
97
+
98
+ ## The complete presentation API [#api]
99
+
100
+ ```ts title="types.ts"
101
+ type PresentationValue =
102
+ | string
103
+ | PresentationPart
104
+ | readonly (string | PresentationPart)[];
105
+
106
+ type PresentationPart =
107
+ | {
108
+ type: "markdown";
109
+ markdown: string;
110
+ }
111
+ | {
112
+ type: "table";
113
+ caption?: string;
114
+ columns: readonly string[];
115
+ rows: readonly (readonly (string | number | boolean | null)[])[];
116
+ }
117
+ | {
118
+ type: "image";
119
+ base64: string;
120
+ mimeType: `image/${string}`;
121
+ alt: string;
122
+ }
123
+ | {
124
+ type: "file";
125
+ url: string;
126
+ name: string;
127
+ mimeType?: string;
128
+ size?: number;
129
+ description?: string;
130
+ };
131
+ ```
132
+
133
+ Strings are normalized to Markdown parts. The builders make each part explicit; validation and defensive copying happen only when a surface materializes the presentation:
134
+
135
+ | Builder | Required fields | Purpose |
136
+ | --- | --- | --- |
137
+ | `present.table()` | `columns`, `rows` | Structured scalar data that can become a terminal or Markdown table |
138
+ | `present.image()` | `base64`, `mimeType`, `alt` | An inline image for surfaces that support image content |
139
+ | `present.file()` | `url`, `name` | A reference to a downloadable or otherwise addressable resource |
140
+
141
+ An image is inline because image-capable protocols commonly need its bytes. A file is deliberately a reference: Capable transports its URL and metadata, not the file body. If an image should stay lazy, represent it as a file with an image MIME type instead. Fetching, authentication, expiry, and storage remain the application's responsibility.
142
+
143
+ ## Surface behavior [#surfaces]
144
+
145
+ Each surface chooses whether to request a presentation and how to lower its parts.
146
+
147
+ An empty array means that no presentation is available, so the surface falls back to canonical output. Return an explicit empty Markdown string only when blank presentation output is intentional.
148
+
149
+ | Surface | Behavior |
150
+ | --- | --- |
151
+ | Typed App call | Returns canonical output and does not run `toPresentation` |
152
+ | CLI | Renders the general Markdown representation with terminal styling |
153
+ | CLI `--json` | Prints canonical output and does not run `toPresentation` |
154
+ | HTTP JSON | Returns canonical output and does not run `toPresentation` |
155
+ | HTTP `Accept: text/markdown` | Returns the general Markdown representation |
156
+ | MCP | Sends text, images, and resource links using native MCP content blocks |
157
+ | Other surfaces | May support, partially lower, or ignore presentations |
158
+
159
+ This is a portable presentation model, not an MCP authoring API and not a UI component framework. It has no JSX, layout system, callbacks, or protocol-specific fields. New part types should be added only when several surfaces can give them a useful meaning.
160
+
161
+ </DocsPage>
@@ -0,0 +1,74 @@
1
+ ---
2
+ title: "Any Fetch host"
3
+ description: "A Capable server is a fetch handler, so any Web-standard host can mount it."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/hosting/fetch", frontmatter);
9
+
10
+ <DocsPage href="/hosting/fetch" frontmatter={frontmatter}>
11
+
12
+ `createServer()` returns an object with one method. Any runtime or framework that can produce a `Request` and return a `Response` can host it, and no Capable-specific adapter is involved.
13
+
14
+ ## The whole contract [#contract]
15
+
16
+ ```ts title="hosting contract"
17
+ type CapableServer = {
18
+ fetch(request: Request): Promise<Response>;
19
+ };
20
+ ```
21
+
22
+ Hand it every path the app owns and keep the rest of your routes as they are. Passing the original request preserves the URL, method, and headers that the mounts match on.
23
+
24
+ ## Bun, Node, Deno, and workers [#bun]
25
+
26
+ ```ts title="server.ts"
27
+ import server from "./capable.server";
28
+
29
+ Bun.serve({ port: 3000, fetch: server.fetch });
30
+ ```
31
+
32
+ Node can use `@hono/node-server` or any adapter that converts an incoming message into a fetch request. Edge runtimes and workers already speak this interface.
33
+
34
+ ## Hono [#hono]
35
+
36
+ ```ts title="server.ts"
37
+ import { Hono } from "hono";
38
+ import server from "./capable.server";
39
+
40
+ const app = new Hono();
41
+
42
+ app.get("/", (c) => c.html(renderProduct()));
43
+
44
+ app.all("/api", (c) => server.fetch(c.req.raw));
45
+ app.all("/api/*", (c) => server.fetch(c.req.raw));
46
+ app.all("/_capable/*", (c) => server.fetch(c.req.raw));
47
+ app.all("/openapi.json", (c) => server.fetch(c.req.raw));
48
+ app.all("/mcp", (c) => server.fetch(c.req.raw));
49
+
50
+ export default app;
51
+ ```
52
+
53
+ ## H3 [#h3]
54
+
55
+ `event.req` is already a web request, so the handler is a direct pass-through.
56
+
57
+ ```ts title="server.ts"
58
+ import { H3, serve } from "h3";
59
+ import server from "./capable.server";
60
+
61
+ const app = new H3()
62
+ .get("/", () => "Existing H3 application")
63
+ .all("/api/**", (event) => server.fetch(event.req))
64
+ .all("/_capable/**", (event) => server.fetch(event.req))
65
+ .all("/openapi.json", (event) => server.fetch(event.req));
66
+
67
+ serve(app, { port: 3000 });
68
+ ```
69
+
70
+ > **Adapters translate, they do not decide**
71
+ >
72
+ > A host converts its request into a fetch request and nothing else. Which surfaces exist, how context is built, and what a capability means stay in `capable.server.ts`.
73
+
74
+ </DocsPage>
@@ -0,0 +1,77 @@
1
+ ---
2
+ title: "Next.js"
3
+ description: "Mount a Capable server inside a Next.js App Router project."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/hosting/next", frontmatter);
9
+
10
+ <DocsPage href="/hosting/next" frontmatter={frontmatter}>
11
+
12
+ Keep the product, authentication, middleware, and deployment you already have. The Next adapter turns the same fetch server into App Router method exports.
13
+
14
+ ## Create the handlers [#handlers]
15
+
16
+ Compose the server once in a shared module. The adapter only maps methods; execution and context stay framework-independent.
17
+
18
+ ```ts title="capable/server.ts"
19
+ // capable/server.ts
20
+ import { createNextRouteHandlers } from "@capable/next";
21
+ import { protocol, createServer, http } from "capable-kit/server";
22
+ import definition from "../capable.app";
23
+
24
+ const server = createServer(definition, {
25
+ context: ({ request }) => contextFromRequest(request),
26
+ mounts: [protocol(), http()],
27
+ });
28
+
29
+ export const { DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT } =
30
+ createNextRouteHandlers(server.fetch);
31
+ ```
32
+
33
+ ## Choose which paths exist [#routes]
34
+
35
+ Route folders decide what is reachable. Export only the methods a path should answer.
36
+
37
+ ```ts title="App Router"
38
+ // app/api/[[...path]]/route.ts
39
+ export { DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT } from "@/capable/server";
40
+
41
+ // app/%5Fcapable/[[...path]]/route.ts
42
+ // %5F keeps Next from treating _capable as a private folder.
43
+ export { GET, POST } from "@/capable/server";
44
+
45
+ // app/openapi.json/route.ts
46
+ export { GET } from "@/capable/server";
47
+ ```
48
+
49
+ | Route | Serves |
50
+ | --- | --- |
51
+ | `/api/*` | Derived or authored HTTP routes |
52
+ | `/_capable/*` | Capable transport for remote apps, the CLI, and React Query |
53
+ | `/openapi.json` | Generated OpenAPI document |
54
+ | `/mcp` | MCP, when the mcp() mount is included |
55
+
56
+ ## Server components and actions [#server-components]
57
+
58
+ Inside the same deployment, do not go through HTTP. Create a local app and call it directly from a server component or a server action; the browser can still reach the same capabilities through `/_capable/*`.
59
+
60
+ ```ts title="app/todo-actions.ts"
61
+ // app/todo-actions.ts
62
+ "use server";
63
+
64
+ import { createApp } from "capable-kit";
65
+ import definition from "../capable.app";
66
+
67
+ export async function createTodo(title: string) {
68
+ const app = createApp(definition, { context: contextFromSession });
69
+ return app.todos.create({ title });
70
+ }
71
+ ```
72
+
73
+ > **One capability, two callers**
74
+ >
75
+ > The server action and the browser query hit the same capability with the same validation and middleware. Only the placement differs.
76
+
77
+ </DocsPage>