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,80 @@
1
+ ---
2
+ title: "React Query"
3
+ description: "Derive query keys, query options, and mutations for TanStack Query."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/surfaces/react-query", frontmatter);
9
+
10
+ <DocsPage href="/surfaces/react-query" frontmatter={frontmatter}>
11
+
12
+ `@capable/react-query` mirrors the app tree into TanStack Query primitives. Keys, query functions, and mutation functions are derived, so components stop repeating endpoint names and cache keys.
13
+
14
+ ## Create the client [#create]
15
+
16
+ Point it at any app. In the browser this is usually a remote app over the Capable transport; on the server it can be a local app. Both App creation and the React Query projection are synchronous. Manifest discovery is deferred until a query actually executes.
17
+
18
+ ```ts title="query.ts"
19
+ import { createRemoteApp } from "capable-kit";
20
+ import { createHttpTransport } from "capable-kit/http";
21
+ import { createReactQuery } from "@capable/react-query";
22
+ import type definition from "../capable.app";
23
+
24
+ const app = createRemoteApp<typeof definition>(
25
+ createHttpTransport({ url: "/_capable/" }),
26
+ );
27
+
28
+ export const query = createReactQuery(app);
29
+ ```
30
+
31
+ ## Use it in components [#use]
32
+
33
+ ```tsx title="todo-list.tsx"
34
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
35
+ import { query } from "./query";
36
+
37
+ export function TodoList() {
38
+ const client = useQueryClient();
39
+ const todos = useQuery(query.todos.list.queryOptions({}));
40
+
41
+ const createTodo = useMutation(
42
+ query.todos.create.mutationOptions({
43
+ onSuccess: () =>
44
+ client.invalidateQueries({ queryKey: query.todos.list.queryKey() }),
45
+ }),
46
+ );
47
+
48
+ if (todos.isPending) return <Spinner />;
49
+ if (todos.error) return <Error error={todos.error} />;
50
+
51
+ return (
52
+ <>
53
+ <ul>{todos.data.map((todo) => <li key={todo.id}>{todo.title}</li>)}</ul>
54
+ <button onClick={() => createTodo.mutate({ title: "New" })}>Add</button>
55
+ </>
56
+ );
57
+ }
58
+ ```
59
+
60
+ | Method | Returns |
61
+ | --- | --- |
62
+ | `queryKey(input?)` | `["capable", ...path, input?]`, for invalidation |
63
+ | `queryOptions(input, options?)` | Options for `useQuery`, with the signal wired to cancellation |
64
+ | `mutationOptions(options?)` | Options for `useMutation`, taking the input as variables |
65
+ | `liveQueryOptions(input, options?)` | Streamed query, only on subscribable read capabilities |
66
+
67
+ Pass `keyPrefix` to `createReactQuery()` if the `capable` prefix collides with existing keys.
68
+
69
+ ## Live queries [#live]
70
+
71
+ When a capability defines [subscribe](/patterns/subscriptions), `liveQueryOptions()` appears on it and each replacement lands in the same cache entry.
72
+
73
+ ```tsx title="todo-list.tsx"
74
+ // Backed by the capability's subscribe(), streamed into the same cache entry.
75
+ const todos = useQuery(query.todos.list.liveQueryOptions({}));
76
+ ```
77
+
78
+ > The projection stays at the data layer. Loading states, error rendering, optimistic updates, and layout remain ordinary React Query and React code.
79
+
80
+ </DocsPage>
@@ -0,0 +1,123 @@
1
+ ---
2
+ title: "TypeScript"
3
+ description: "Call capabilities as typed functions, in this process or across a transport."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/surfaces/typescript", frontmatter);
9
+
10
+ <DocsPage href="/surfaces/typescript" frontmatter={frontmatter}>
11
+
12
+ The TypeScript surface is the app itself. An app is a callable tree, so calling a capability is an ordinary function call with an awaited result. There is no client to generate, no request object to build, and no route to remember.
13
+
14
+ ## Calling a capability [#call]
15
+
16
+ Each leaf of the tree is a function that takes the capability's input and resolves to its output. Both are inferred from the definition, so renaming a field or adding an error is a compile error at every call site.
17
+
18
+ ```ts title="script.ts"
19
+ import { createApp } from "capable-kit";
20
+ import definition from "./capable.app";
21
+
22
+ const app = createApp(definition);
23
+
24
+ // Input is checked against the capability's schema.
25
+ const todos = await app.todos.list({ status: "open" });
26
+ // ^? Todo[]
27
+
28
+ await app.todos.create({ title: "Write the docs" });
29
+ ```
30
+
31
+ | Argument | Meaning |
32
+ | --- | --- |
33
+ | `input` | Validated against the capability schema. Optional when the capability declares no input. |
34
+ | `options.signal` | An `AbortSignal` passed to the handler and, for a remote app, to the underlying request. |
35
+
36
+ ## Calling a remote app [#remote]
37
+
38
+ [A remote app](/patterns/remote-apps) has the identical shape. The definition is imported as a _type_, so nothing from the server bundles into the caller and no client is generated.
39
+
40
+ ```ts title="client.ts"
41
+ import { createRemoteApp } from "capable-kit";
42
+ import { createHttpTransport } from "capable-kit/http";
43
+ import type definition from "../server/capable.app";
44
+
45
+ // Same tree, same types, different placement.
46
+ const app = createRemoteApp<typeof definition>(
47
+ createHttpTransport({ url: "https://todos.example.com/_capable/" }),
48
+ );
49
+
50
+ const todos = await app.todos.list({ status: "open" });
51
+ // ^? Todo[]
52
+ ```
53
+
54
+ Everything below applies to both. Code that takes an app as a parameter does not need to know which one it received.
55
+
56
+ ## Errors [#errors]
57
+
58
+ Declared errors survive the boundary. The same guard narrows a local throw and a decoded remote failure, with typed `data` either way. Anything undeclared arrives as an internal error.
59
+
60
+ ```ts title="caller.ts"
61
+ import { TodoErrors } from "./errors";
62
+
63
+ try {
64
+ await app.todos.delete({ todoId });
65
+ } catch (error) {
66
+ if (TodoErrors.NOT_FOUND.is(error)) {
67
+ console.error(error.data.todoId); // typed
68
+ return;
69
+ }
70
+ throw error;
71
+ }
72
+ ```
73
+
74
+ The full model, including which failures belong in a contract, is on the [errors page](/concepts/errors).
75
+
76
+ ## Cancellation [#cancellation]
77
+
78
+ Pass a signal as the second argument. A local call forwards it to the handler; a remote call also aborts the in-flight request.
79
+
80
+ ```ts title="script.ts"
81
+ const controller = new AbortController();
82
+ setTimeout(() => controller.abort(), 2_000);
83
+
84
+ const todos = await app.todos.list({}, { signal: controller.signal });
85
+ ```
86
+
87
+ ## Streaming reads [#subscribe]
88
+
89
+ When a capability defines [subscribe](/patterns/subscriptions), pass its call to `subscribe()` to get an async iterator instead of a single result. Calling it normally still returns one value.
90
+
91
+ ```ts title="watch.ts"
92
+ import { subscribe } from "capable-kit";
93
+
94
+ for await (const todos of subscribe(app.todos.list, { status: "open" })) {
95
+ render(todos); // each value is a complete replacement
96
+ }
97
+ ```
98
+
99
+ > `subscribe()` takes the capability function itself, not its result, which is why it stays fully typed: `subscribe(app.todos.list, input)`.
100
+
101
+ ## One capability without an app [#without-app]
102
+
103
+ Tests and scripts sometimes want a single capability with no tree around it. `executeCapability()` runs it directly. Group middleware, group errors, and group metadata do not apply, because there is no group.
104
+
105
+ ```ts title="list-todos.test.ts"
106
+ import { executeCapability } from "capable-kit";
107
+ import { listTodos } from "./capabilities/list-todos";
108
+
109
+ const todos = await executeCapability(listTodos, {
110
+ input: { status: "open" },
111
+ context: { todos: store },
112
+ });
113
+ ```
114
+
115
+ ## Limits of this surface [#notes]
116
+
117
+ | Not this | Instead |
118
+ | --- | --- |
119
+ | A generated SDK | Types come from a type-only import of the definition; the tree is a proxy built from the manifest. |
120
+ | A place for presentation | Titles, routes, and tool names belong to [surface metadata](/reference/metadata), not to the call. |
121
+ | A cache or a UI binding | Use [React Query](/surfaces/react-query) for keys, caching, and live queries in a React app. |
122
+
123
+ </DocsPage>
@@ -0,0 +1,78 @@
1
+ ---
2
+ title: "Surfaces"
3
+ description: "A surface is a projection of an app. You choose which ones exist."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/surfaces", frontmatter);
9
+
10
+ <DocsPage href="/surfaces" frontmatter={frontmatter}>
11
+
12
+ Surfaces are the only place where presentation lives. They read the app manifest and the metadata relevant to them, and they never change what a capability means.
13
+
14
+ ## Two kinds of surface [#kinds]
15
+
16
+ Some surfaces are network mounts on a server. Others are projections of an app inside a process. Both consume the same app.
17
+
18
+ ```ts title="capable.server.ts"
19
+ import { mcp } from "capable-kit/mcp";
20
+ import { protocol, createServer, http } from "capable-kit/server";
21
+ import definition from "./capable.app";
22
+
23
+ export default createServer(definition, {
24
+ context: ({ request }) => contextFromRequest(request),
25
+ mounts: [
26
+ protocol({ path: "/_capable" }),
27
+ http({ path: "/api", openapiPath: "/openapi.json" }),
28
+ mcp({ path: "/mcp" }),
29
+ ],
30
+ });
31
+ ```
32
+
33
+ A projection needs no server at all. It takes an executable app and returns commands, tools, or query options.
34
+
35
+ ```ts title="tools.ts"
36
+ import { createCli } from "capable-kit/cli";
37
+ import { createAiSdkTools } from "capable-kit/ai-sdk";
38
+ import { createEveTools } from "capable-kit/eve";
39
+ import { createReactQuery } from "@capable/react-query";
40
+
41
+ createCli(app); // process-level command tree
42
+ await createAiSdkTools(app); // typed AI SDK tools
43
+ createEveTools(app); // durable in-process agent tools
44
+ createReactQuery(app); // query keys and options for a UI
45
+ ```
46
+
47
+ ## Choosing surfaces [#choose]
48
+
49
+ | Surface | Use it when | Entry point |
50
+ | --- | --- | --- |
51
+ | [TypeScript](/surfaces/typescript) | Code calls the capability directly, here or over a transport | `capable` |
52
+ | [HTTP and OpenAPI](/surfaces/http) | Third parties or other services call you | `capable/server` |
53
+ | Capable transport | A Capable client, CLI, or another app calls you | `capable/server` |
54
+ | [CLI](/surfaces/cli) | People or scripts drive it from a terminal | `capable/cli` |
55
+ | [MCP](/surfaces/mcp) | External agents connect over the network | `capable/mcp` |
56
+ | [Eve](/surfaces/eve) | An agent runs in your process | `capable/eve` |
57
+ | [AI SDK](/surfaces/ai-sdk) | An AI SDK model or agent calls your app | `capable/ai-sdk` |
58
+ | [React Query](/surfaces/react-query) | A React UI reads and mutates the app | `@capable/react-query` |
59
+
60
+ > **Nothing is implicit**
61
+ >
62
+ > A capability does not become a route, a command, or a tool until a surface is mounted or projected. Use [selectApp()](/patterns/composition) when a surface should see less than the whole app.
63
+
64
+ ## Metadata belongs to one surface [#metadata]
65
+
66
+ `meta.http` only affects HTTP, `meta.cli` only affects the CLI, and so on. Metadata can rename, reroute, or hide a capability on its surface; it can never change validation, errors, or the result. The full list is in the [metadata reference](/reference/metadata).
67
+
68
+ ## Surface guides [#pages]
69
+
70
+ - [**TypeScript**](/surfaces/typescript) — Typed calls, cancellation, errors, and streaming reads.
71
+ - [**HTTP and OpenAPI**](/surfaces/http) — Derived routes, authored routes, and the generated document.
72
+ - [**CLI**](/surfaces/cli) — Commands, flags, help, and remote invocation.
73
+ - [**MCP**](/surfaces/mcp) — Tools, names, and safety hints for external agents.
74
+ - [**AI SDK**](/surfaces/ai-sdk) — Typed tools for generateText, streamText, and agents.
75
+ - [**Eve**](/surfaces/eve) — Native in-process tools with approvals.
76
+ - [**React Query**](/surfaces/react-query) — Query keys, mutations, and live queries.
77
+
78
+ </DocsPage>
@@ -0,0 +1,99 @@
1
+ ---
2
+ title: "Why Capable"
3
+ description: "What it costs to hand-write the same capability for every interface, and what changes when you stop."
4
+ ---
5
+
6
+ import { DocsPage, docMetadata } from "../_components/docs-page";
7
+
8
+ export const metadata = docMetadata("/why-capable", frontmatter);
9
+
10
+ <DocsPage href="/why-capable" frontmatter={frontmatter}>
11
+
12
+ One capability, four callers: the product UI, an HTTP API, a terminal, and an agent. Capable exists because writing that capability four times is the normal way to do it, and it does not hold up.
13
+
14
+ ## One surface is not a product [#assumption]
15
+
16
+ Agents now take part in workflows that used to be clicks. Teams reach for a terminal for the things a dashboard is bad at. MCP turned "can another agent call this?" into a routine requirement.
17
+
18
+ So the interesting question is not how to ship the first interface. It is what the second and third cost you.
19
+
20
+ ## The second surface is where it stalls [#cost]
21
+
22
+ Ask an AI for a todo app and you get a good Next.js app with no API in it. A server component reads the database, a server action writes to it, the session comes from a cookie, and the input shape lives in a form. That is reachable from a browser and from nowhere else.
23
+
24
+ ```ts title="app/actions.ts"
25
+ // app/actions.ts — what you actually get from a prompt
26
+ "use server";
27
+
28
+ export async function createTodo(formData: FormData) {
29
+ const { userId } = await auth(); // cookie session
30
+ await db.insert(todos).values({
31
+ userId,
32
+ title: String(formData.get("title")), // no schema anywhere
33
+ });
34
+ revalidatePath("/todos");
35
+ }
36
+ ```
37
+
38
+ A CLI is not a view of that app. It is a separate program on the far side of a network boundary, so "add a CLI" is really five tasks, and only the capable one is the CLI.
39
+
40
+ ```ts title="by hand"
41
+ // 1. an API that did not exist before
42
+ export async function POST(request: Request) {
43
+ const { userId } = await authFromBearerToken(request); // 2. non-cookie auth
44
+ const input = TodoInput.parse(await request.json()); // 3. a schema, finally
45
+ return Response.json(await createTodo(userId, input));
46
+ }
47
+
48
+ // 4. the CLI, restating the same schema a second time
49
+ program
50
+ .command("create <title>")
51
+ .option("--due-date <date>")
52
+ .action(async (title, options) => {
53
+ const res = await fetch(`${baseUrl}/api/todos`, { /* ... */ });
54
+ if (!res.ok) printError(await res.json()); // 5. a second error format
55
+ });
56
+ ```
57
+
58
+ A command framework helps with the argument parsing and nothing else. You still extract the API, invent token auth, describe the input twice, and map errors twice. None of it is hard, which is the problem: it is a pile of low-information code that has to be redone whenever the capability changes. That is also why asking a generator for "a web app, a CLI, and an MCP server" gives you three things that disagree by the second change.
59
+
60
+ ## Put the capability under the interfaces [#model]
61
+
62
+ In Capable the capability owns the semantics and each surface only decides how it is presented.
63
+
64
+ | Concern | Owner |
65
+ | --- | --- |
66
+ | Input, output, errors, middleware, handler | The capability |
67
+ | Execution placement and context | The app |
68
+ | Method, command name, tool name, query key | The surface |
69
+ | Requests, deployment, runtime | The host |
70
+
71
+ Because the capability is the API, there is nothing to extract when the second caller shows up. The whole CLI becomes the file below: commands, flags, help text, validation, and errors come from the same capabilities the HTTP surface serves, so a command cannot accept input the route rejects.
72
+
73
+ ```ts title="cli.ts"
74
+ #!/usr/bin/env bun
75
+ import { createApp } from "capable-kit";
76
+ import { createCli } from "capable-kit/cli";
77
+ import definition from "./capable.app";
78
+
79
+ const app = createApp(definition, { context: createContext });
80
+ process.exit(await createCli(app, { invocationName: "todo" }).run(process.argv.slice(2)));
81
+ ```
82
+
83
+ Swap `createApp` for `createRemoteApp` and that same file drives a deployed server. The same definition is also the MCP server, the OpenAPI document, and the typed client.
84
+
85
+ ## When not to use it [#tradeoffs]
86
+
87
+ - **One caller, forever.** A single webhook receiver is simpler as a plain route handler.
88
+ - **No schemas.** Ad-hoc payloads do not project into commands or tools.
89
+ - **No appetite for vocabulary.** Capabilities, apps, surfaces, and placement are concepts your team has to learn.
90
+
91
+ ## Adopting it gradually [#adopt]
92
+
93
+ Capable is not a rewrite. Define one capability, mount it in the server you already run, add surfaces when you need them.
94
+
95
+ - [**Keep your host**](/hosting/next) — Mount a fetch handler in Next.js, Hono, H3, or Bun.
96
+ - [**Choose surfaces**](/surfaces) — Nothing is exposed until you mount or project it.
97
+ - [**Compose later**](/patterns/composition) — Merge local and remote apps once more than one exists.
98
+
99
+ </DocsPage>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "capable-kit",
3
- "version": "0.0.1-alpha.3",
3
+ "version": "0.0.1-alpha.5",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "cap": "dist/bin.mjs",
@@ -45,10 +45,20 @@
45
45
  }
46
46
  },
47
47
  "files": [
48
- "dist",
48
+ "dist/*.d.mts",
49
+ "dist/*.mjs",
50
+ "dist/*.mjs.map",
51
+ "docs",
49
52
  "src",
50
53
  "README.md"
51
54
  ],
55
+ "directories": {
56
+ "doc": "./docs"
57
+ },
58
+ "scripts": {
59
+ "prepack": "node package-docs.mjs",
60
+ "postpack": "node package-docs.mjs --clean"
61
+ },
52
62
  "engines": {
53
63
  "node": ">=20"
54
64
  },
@@ -58,7 +68,7 @@
58
68
  },
59
69
  "dependencies": {
60
70
  "@standard-schema/spec": "^1.1.0",
61
- "@modelcontextprotocol/sdk": "^1.29.0",
71
+ "@modelcontextprotocol/server": "^2.0.0",
62
72
  "markdansi": "0.3.2",
63
73
  "nitro": "3.0.260610-beta"
64
74
  },
package/src/index.test.ts CHANGED
@@ -34,6 +34,7 @@ describe("capable public entry points", () => {
34
34
  "group",
35
35
  "md",
36
36
  "mergeApps",
37
+ "present",
37
38
  "selectApp",
38
39
  "subscribe",
39
40
  "watchQuery",
package/src/index.ts CHANGED
@@ -4,13 +4,17 @@ export {
4
4
  executeCapability,
5
5
  group,
6
6
  md,
7
+ present,
7
8
  capability,
8
9
  watchQuery,
9
10
  type AppContext,
10
11
  type AppDefinition,
11
12
  type DefinedErrors,
12
13
  type ExecuteCapabilityOptions,
13
- type MarkdownRenderer,
14
+ type PresentationPart,
15
+ type PresentationRenderer,
16
+ type PresentationTableCell,
17
+ type PresentationValue,
14
18
  type CapabilityDefinition,
15
19
  type CapabilityContext,
16
20
  type CapabilityEffect,
@@ -0,0 +1,102 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { describe, expect, test } from "vitest";
7
+
8
+ const packageDirectory = fileURLToPath(new URL("../", import.meta.url));
9
+
10
+ type PackFile = {
11
+ readonly path: string;
12
+ };
13
+
14
+ type PackResult = {
15
+ readonly filename: string;
16
+ readonly files: readonly PackFile[];
17
+ };
18
+
19
+ describe("published package", () => {
20
+ test("includes the public and internal documentation", () => {
21
+ const destination = mkdtempSync(join(tmpdir(), "capable-pack-"));
22
+
23
+ try {
24
+ const output = execFileSync(
25
+ "pnpm",
26
+ ["pack", "--json", "--pack-destination", destination],
27
+ {
28
+ cwd: packageDirectory,
29
+ encoding: "utf8",
30
+ },
31
+ );
32
+ const result = JSON.parse(output) as PackResult;
33
+ const paths = new Set(result.files.map((file) => file.path));
34
+ const manifest = JSON.parse(
35
+ execFileSync(
36
+ "tar",
37
+ ["-xOzf", result.filename, "package/package.json"],
38
+ { encoding: "utf8" },
39
+ ),
40
+ ) as {
41
+ readonly directories?: { readonly doc?: string };
42
+ readonly scripts?: Record<string, string>;
43
+ };
44
+ const quickstart = execFileSync(
45
+ "tar",
46
+ [
47
+ "-xOzf",
48
+ result.filename,
49
+ "package/docs/site/quickstart.mdx",
50
+ ],
51
+ { encoding: "utf8" },
52
+ );
53
+
54
+ expect(paths).toContain("docs/README.md");
55
+ expect(paths).toContain("docs/CONTEXT.md");
56
+ expect(paths).toContain("docs/internal/architecture.md");
57
+ expect(paths).toContain(
58
+ "docs/internal/adr/0001-capability-is-the-semantic-boundary.md",
59
+ );
60
+ expect(paths).toContain("docs/site/quickstart.mdx");
61
+ expect(paths).toContain(
62
+ "docs/site/reference/packages-and-entry-points.mdx",
63
+ );
64
+ expect(
65
+ [...paths].filter(
66
+ (path) =>
67
+ path.startsWith("docs/site/") && path.endsWith(".mdx"),
68
+ ),
69
+ ).toHaveLength(26);
70
+ expect(paths).toContain("docs/site/introduction.mdx");
71
+ expect(paths).toContain("docs/site/concepts/presentations.mdx");
72
+ expect(
73
+ [...paths].some(
74
+ (path) =>
75
+ path.startsWith("docs/site/") &&
76
+ (path.endsWith("/page.tsx") || path.endsWith("/page.mdx")),
77
+ ),
78
+ ).toBe(false);
79
+ expect(paths).not.toContain("docs/site/globals.css");
80
+ expect(
81
+ [...paths].some(
82
+ (path) => path.startsWith("dist/package/") || path.endsWith(".tgz"),
83
+ ),
84
+ ).toBe(false);
85
+ expect(paths).not.toContain("package-docs.mjs");
86
+ expect(manifest.directories?.doc).toBe("./docs");
87
+ expect(manifest.scripts?.prepack).toBeUndefined();
88
+ expect(manifest.scripts?.postpack).toBeUndefined();
89
+ expect(quickstart).toMatch(
90
+ /^---\ntitle: "Quickstart"\ndescription: ".+"\n---/,
91
+ );
92
+
93
+ expect(existsSync(new URL("../docs/", import.meta.url))).toBe(false);
94
+ } finally {
95
+ rmSync(destination, { force: true, recursive: true });
96
+ rmSync(new URL("../docs/", import.meta.url), {
97
+ force: true,
98
+ recursive: true,
99
+ });
100
+ }
101
+ });
102
+ });
@@ -1 +0,0 @@
1
- {"version":3,"file":"mount--YHrgRHJ.mjs","names":[],"sources":["../../mcp/src/index.ts","../../mcp/src/mount.ts"],"sourcesContent":["import type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n getAppRuntime,\n type AnyApp,\n type JsonSchema,\n type ManifestNode,\n type ManifestCapability,\n type CapabilityResult,\n} from \"@capable/app\";\n\nexport type McpCapabilityMeta =\n | false\n | {\n readonly name?: string;\n };\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly mcp?: McpCapabilityMeta;\n }\n}\n\nexport type McpTool = {\n readonly name: string;\n readonly title?: string;\n readonly description?: string;\n readonly inputSchema: JsonSchema;\n readonly outputSchema?: JsonSchema;\n readonly annotations: {\n readonly readOnlyHint: boolean;\n readonly destructiveHint: boolean;\n };\n call(\n input: unknown,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapabilityResult>;\n};\n\nexport async function createMcp(\n app: AnyApp,\n): Promise<readonly McpTool[]> {\n const runtime = getAppRuntime(app);\n const manifest = await runtime.manifest();\n const tools = flatten(manifest.capabilities)\n .filter((capability) => capability.meta.mcp !== false)\n .map((capability) => {\n const meta = capability.meta.mcp as Exclude<McpCapabilityMeta, false> | undefined;\n return Object.freeze({\n name: meta?.name ?? capability.path.join(\"__\"),\n ...(capability.title ? { title: capability.title } : {}),\n ...(capability.description ? { description: capability.description } : {}),\n inputSchema: capability.input ?? {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n ...(capability.output\n ? { outputSchema: mcpOutputSchema(capability.output) }\n : {}),\n annotations: {\n readOnlyHint: capability.effect === \"read\",\n destructiveHint: capability.effect === \"destructive\",\n },\n call(input: unknown, options?: { readonly signal?: AbortSignal }) {\n return runtime.call({\n id: capability.id,\n input,\n ...(options?.signal ? { signal: options.signal } : {}),\n });\n },\n });\n });\n const names = new Set<string>();\n for (const tool of tools) {\n if (names.has(tool.name)) {\n throw new Error(`Duplicate MCP tool name \"${tool.name}\"`);\n }\n names.add(tool.name);\n }\n return tools;\n}\n\nfunction mcpOutputSchema(schema: JsonSchema): JsonSchema {\n if (schema.type === \"object\") return schema;\n return {\n type: \"object\",\n properties: { value: schema },\n required: [\"value\"],\n additionalProperties: false,\n };\n}\n\nfunction flatten(nodes: readonly ManifestNode[]): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n","import type { ServerMount } from \"@capable/server\";\nimport { createApp, TransportError } from \"@capable/app\";\nimport { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport { WebStandardStreamableHTTPServerTransport } from \"@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js\";\nimport {\n CallToolRequestSchema,\n type CallToolResult,\n ListToolsRequestSchema,\n type Tool,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { createMcp, type McpTool } from \"./index.ts\";\n\nexport function mcp<TContext = any>(\n options: {\n readonly path?: string;\n readonly name?: string;\n readonly version?: string;\n } = {},\n): ServerMount<TContext> {\n const path = normalizePath(options.path ?? \"/mcp\");\n return {\n kind: \"capable.server.mount\",\n compile(app, context) {\n return {\n name: \"mcp\",\n async fetch(request) {\n if (new URL(request.url).pathname !== path) return undefined;\n const executable = createApp(\n app,\n context\n ? { context: () => context({ request }) }\n : undefined as never,\n );\n const tools = await createMcp(executable);\n const server = createMcpServer(tools, {\n name: options.name ?? app.name ?? \"capable\",\n version: options.version ?? app.version ?? \"0.0.0\",\n });\n const transport = new WebStandardStreamableHTTPServerTransport({\n enableJsonResponse: true,\n });\n await server.connect(transport);\n try {\n return await transport.handleRequest(request);\n } finally {\n await transport.close();\n await server.close();\n }\n },\n };\n },\n };\n}\n\nfunction createMcpServer(\n tools: readonly McpTool[],\n info: { readonly name: string; readonly version: string },\n): Server {\n const server = new Server(info, {\n capabilities: { tools: {} },\n });\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: tools.map(toProtocolTool),\n }));\n server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n const tool = tools.find(({ name }) => name === request.params.name);\n if (!tool) {\n return toolError(`Unknown tool \"${request.params.name}\"`);\n }\n try {\n const result = await tool.call(request.params.arguments ?? {}, {\n signal: extra.signal,\n });\n return {\n content: [{\n type: \"text\",\n text: result.markdown ?? stringify(result.output),\n }],\n structuredContent: isRecord(result.output)\n ? result.output\n : { value: result.output },\n } satisfies CallToolResult;\n } catch (error) {\n if (!(error instanceof TransportError)) throw error;\n return toolError(error.message, {\n code: error.code,\n status: error.status,\n data: error.data,\n });\n }\n });\n return server;\n}\n\nfunction toProtocolTool(tool: McpTool): Tool {\n return {\n name: tool.name,\n ...(tool.title ? { title: tool.title } : {}),\n ...(tool.description ? { description: tool.description } : {}),\n inputSchema: tool.inputSchema as Tool[\"inputSchema\"],\n ...(tool.outputSchema\n ? { outputSchema: tool.outputSchema as Tool[\"outputSchema\"] }\n : {}),\n annotations: tool.annotations,\n };\n}\n\nfunction toolError(\n message: string,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n isError: true,\n content: [{\n type: \"text\",\n text: details ? JSON.stringify({ message, ...details }) : message,\n }],\n };\n}\n\nfunction stringify(value: unknown): string {\n return typeof value === \"string\"\n ? value\n : JSON.stringify(value) ?? String(value);\n}\n\nfunction normalizePath(value: string): string {\n return `/${value.split(\"/\").filter(Boolean).join(\"/\")}`;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n"],"mappings":";;;;;AAsCA,eAAsB,UACpB,KAC6B;CAC7B,MAAM,UAAU,cAAc,GAAG;CAEjC,MAAM,QAAQ,SAA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