@shapio/mcp 0.2.0
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.
- package/LICENSE +201 -0
- package/dist/bin.js +24 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +2 -0
- package/dist/options-Bc0S3ldO.js +749 -0
- package/dist/options-Bc0S3ldO.js.map +1 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { n as USAGE, o as createShapioMcpServer, r as parseOptions, t as OptionsError } from "./options-Bc0S3ldO.js";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
|
|
4
|
+
//#region src/bin.ts
|
|
5
|
+
/**
|
|
6
|
+
* `shapio-mcp`: stdio MCP server. stdout carries the protocol, so everything for people goes to stderr.
|
|
7
|
+
*/
|
|
8
|
+
const main = async () => {
|
|
9
|
+
const options = parseOptions(process.argv.slice(2), process.env, process.cwd());
|
|
10
|
+
if (options === "help") {
|
|
11
|
+
process.stderr.write(USAGE);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
await createShapioMcpServer(options).connect(new StdioServerTransport());
|
|
15
|
+
};
|
|
16
|
+
main().catch((error) => {
|
|
17
|
+
const message = error instanceof OptionsError ? `${error.message}\n\n${USAGE}` : error instanceof Error ? error.stack ?? error.message : String(error);
|
|
18
|
+
process.stderr.write(`shapio-mcp: ${message}\n`);
|
|
19
|
+
process.exitCode = 1;
|
|
20
|
+
});
|
|
21
|
+
//#endregion
|
|
22
|
+
export {};
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","names":[],"sources":["../src/bin.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from '@modelcontextprotocol/server/stdio';\nimport { OptionsError, parseOptions, USAGE } from './options.js';\nimport { createShapioMcpServer } from './server.js';\n\n/**\n * `shapio-mcp`: stdio MCP server. stdout carries the protocol, so everything for people goes to stderr.\n */\nconst main = async () => {\n const options = parseOptions(process.argv.slice(2), process.env, process.cwd());\n if (options === 'help') {\n process.stderr.write(USAGE);\n return;\n }\n const server = createShapioMcpServer(options);\n await server.connect(new StdioServerTransport());\n};\n\nmain().catch((error: unknown) => {\n const message =\n error instanceof OptionsError\n ? `${error.message}\\n\\n${USAGE}`\n : error instanceof Error\n ? (error.stack ?? error.message)\n : String(error);\n process.stderr.write(`shapio-mcp: ${message}\\n`);\n process.exitCode = 1;\n});\n"],"mappings":";;;;;;;AAQA,MAAM,OAAO,YAAY;CACvB,MAAM,UAAU,aAAa,QAAQ,KAAK,MAAM,CAAC,GAAG,QAAQ,KAAK,QAAQ,IAAI,CAAC;CAC9E,IAAI,YAAY,QAAQ;EACtB,QAAQ,OAAO,MAAM,KAAK;EAC1B;CACF;CAEA,MADe,sBAAsB,OAC1B,CAAC,CAAC,QAAQ,IAAI,qBAAqB,CAAC;AACjD;AAEA,KAAK,CAAC,CAAC,OAAO,UAAmB;CAC/B,MAAM,UACJ,iBAAiB,eACb,GAAG,MAAM,QAAQ,MAAM,UACvB,iBAAiB,QACd,MAAM,SAAS,MAAM,UACtB,OAAO,KAAK;CACpB,QAAQ,OAAO,MAAM,eAAe,QAAQ,GAAG;CAC/C,QAAQ,WAAW;AACrB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/server";
|
|
2
|
+
import { ShapioClient } from "@shapio/client";
|
|
3
|
+
//#region src/options.d.ts
|
|
4
|
+
/** How the server was started: the Shapio instance, its token, and the two guards. */
|
|
5
|
+
type McpOptions = {
|
|
6
|
+
/** Shapio's base URL including any BASE_PATH (`SHAPIO_URL`). */
|
|
7
|
+
baseUrl: string;
|
|
8
|
+
/** An admin-scope API token (`SHAPIO_TOKEN`). Give its role no `changes.ship`: shipping stays with people. */
|
|
9
|
+
token: string;
|
|
10
|
+
/** Registers `change_sets_ship` (`--allow-ship`). A client-side guard only: the token's role decides. */
|
|
11
|
+
allowShip: boolean;
|
|
12
|
+
/** `media_upload` reads files only under this directory (`--media-root`, default: the working directory). */
|
|
13
|
+
mediaRoot: string;
|
|
14
|
+
/**
|
|
15
|
+
* The site key every request is about (`--site`, else `SHAPIO_SITE`), on multi-site instances. Left out:
|
|
16
|
+
* the token's site (a site token), else the primary site. A site token cannot name another site.
|
|
17
|
+
*/
|
|
18
|
+
site?: string;
|
|
19
|
+
};
|
|
20
|
+
export declare const USAGE = "Usage: shapio-mcp [--allow-ship] [--media-root <dir>] [--site <key>]\n\nA Model Context Protocol server (stdio) for a Shapio instance.\n\nEnvironment:\n SHAPIO_URL Shapio's base URL, including any BASE_PATH (e.g. https://cms.example.com)\n SHAPIO_TOKEN An admin-scope API token. Give its role no \"changes.ship\" permission: agents propose\n change sets, people ship them.\n SHAPIO_SITE The site key to work on (multi-site instances); --site overrides it. Default: the\n token's site, else the primary site.\n\nOptions:\n --allow-ship Offer the change_sets_ship tool (the token's role must also allow changes.ship)\n --media-root <dir> Directory media_upload may read files from (default: the working directory)\n --site <key> The site to work on (overrides SHAPIO_SITE)\n -h, --help Show this help\n";
|
|
21
|
+
export declare class OptionsError extends Error {
|
|
22
|
+
constructor(message: string);
|
|
23
|
+
}
|
|
24
|
+
/** Reads the command line and environment; throws OptionsError with a message meant for stderr. */
|
|
25
|
+
export declare const parseOptions: (argv: readonly string[], env: Readonly<Record<string, string | undefined>>, cwd: string) => McpOptions | "help";
|
|
26
|
+
//#endregion
|
|
27
|
+
//#region src/server.d.ts
|
|
28
|
+
export declare const MCP_SERVER_NAME = "shapio";
|
|
29
|
+
export declare const MCP_SERVER_VERSION: string;
|
|
30
|
+
/** The MCP server for one Shapio instance, with every tool, resource and prompt registered. */
|
|
31
|
+
export declare const createShapioMcpServer: (options: McpOptions, client?: ShapioClient) => McpServer;
|
|
32
|
+
//#endregion
|
|
33
|
+
export type { McpOptions };
|
|
34
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/server";
|
|
2
|
+
import { HEALTH_RULES, ShapioApiError, createClient } from "@shapio/client";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { isModelDefinition, isStableId, routeKeyOf, serializeDefinition } from "@shapio/schema";
|
|
5
|
+
import { realpath } from "node:fs/promises";
|
|
6
|
+
import { isAbsolute, relative, resolve } from "node:path";
|
|
7
|
+
import { uploadFile } from "@shapio/client/node";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { parseArgs } from "node:util";
|
|
10
|
+
//#region package.json
|
|
11
|
+
var version = "0.2.0";
|
|
12
|
+
//#endregion
|
|
13
|
+
//#region src/prompts.ts
|
|
14
|
+
const userMessage = (text) => ({ messages: [{
|
|
15
|
+
role: "user",
|
|
16
|
+
content: {
|
|
17
|
+
type: "text",
|
|
18
|
+
text
|
|
19
|
+
}
|
|
20
|
+
}] });
|
|
21
|
+
/** Starting points for the two jobs agents do most: modelling and reviewing a change set. */
|
|
22
|
+
const registerPrompts = ({ server }) => {
|
|
23
|
+
server.registerPrompt("model_content_type", {
|
|
24
|
+
title: "Model a content type for …",
|
|
25
|
+
description: "Design a content type for something and draft it into a change set for review.",
|
|
26
|
+
argsSchema: z.object({ subject: z.string().min(1).describe("What the content type is for, e.g. \"a blog\"") })
|
|
27
|
+
}, ({ subject }) => userMessage(`Model content types in Shapio for ${subject}.\n\n1. Call schema_list and read the existing types first; reuse or extend them instead of duplicating.
|
|
28
|
+
2. Design the types: API IDs are camelCase GraphQL names, labels are for people; prefer components for repeated groups and relations for shared entities.
|
|
29
|
+
3. Draft each type with schema_draft (one change set for the whole design: pass the changeSetId from the first call to the rest).
|
|
30
|
+
4. Read change_sets_review, fix every blocking issue, and summarise the design and the review for me. Do not ship: I review and ship the change set myself.`));
|
|
31
|
+
server.registerPrompt("review_change_set", {
|
|
32
|
+
title: "Review change set N",
|
|
33
|
+
description: "Explain what a change set would do when it ships, and what to check first.",
|
|
34
|
+
argsSchema: z.object({ changeSetId: z.string().min(1).describe("The change set ID") })
|
|
35
|
+
}, ({ changeSetId }) => userMessage(`Review Shapio change set ${changeSetId}. Call change_sets_review and tell me, briefly:\n- what goes live (schema changes and entries, with the field diffs that matter);
|
|
36
|
+
- anything breaking or destructive, and which API consumers read the affected fields (usage_fields);
|
|
37
|
+
- blocking issues and warnings, and how to fix each;
|
|
38
|
+
- whether you would ship it. Do not ship it yourself.`));
|
|
39
|
+
};
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/definitions.ts
|
|
42
|
+
/** The active schema (the pull format), read fresh for each call: models change live. */
|
|
43
|
+
const readSchema = (client) => client.admin.schema.export();
|
|
44
|
+
/** An active definition by API ID (or stable ID); throws a message the agent can act on. */
|
|
45
|
+
const findDefinition = (schema, key) => {
|
|
46
|
+
const found = schema.definitions.find(({ definition }) => definition.apiKey === key || definition.id === key);
|
|
47
|
+
if (!found) {
|
|
48
|
+
const known = schema.definitions.map(({ definition }) => definition.apiKey).join(", ") || "(none)";
|
|
49
|
+
throw new Error(`No model or component with API ID "${key}". Known: ${known}`);
|
|
50
|
+
}
|
|
51
|
+
return found;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* The delivery route key: a collection's plural API ID (`articles`), a singleton's API ID. The admin content
|
|
55
|
+
* API uses the singular API ID instead. Components have no route.
|
|
56
|
+
*/
|
|
57
|
+
const routeKeyOf$1 = (definition) => {
|
|
58
|
+
if (!isModelDefinition(definition)) throw new Error(`"${definition.apiKey}" is a component: components are read through the models that use them`);
|
|
59
|
+
return routeKeyOf(definition);
|
|
60
|
+
};
|
|
61
|
+
/** A one-line summary per definition, for listings that should not carry every field's settings. */
|
|
62
|
+
const summarize = ({ definition, version }) => ({
|
|
63
|
+
id: definition.id,
|
|
64
|
+
kind: definition.kind,
|
|
65
|
+
apiKey: definition.apiKey,
|
|
66
|
+
...definition.kind === "collection" ? { pluralApiKey: routeKeyOf(definition) } : {},
|
|
67
|
+
label: definition.label,
|
|
68
|
+
version,
|
|
69
|
+
fields: definition.fields.map((field) => ({
|
|
70
|
+
apiKey: field.apiKey,
|
|
71
|
+
type: field.type,
|
|
72
|
+
required: field.required,
|
|
73
|
+
localized: field.localized
|
|
74
|
+
}))
|
|
75
|
+
});
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/generated/deliveryApiDoc.ts
|
|
78
|
+
const DELIVERY_API_DOC = "# Delivery API (REST)\n\nYour sites and apps read published content from one generic route per model:\n\n```text\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<plural API ID> # a collection: a page of entries\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<plural API ID>/<entry id> # a collection: one entry\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<API ID> # a single type: its entry\n```\n\nA collection is addressed by its **plural API ID** (`/api/content/articles`), a single type by its **API ID**\n(`/api/content/homepage`). The singular API ID of a collection is not a delivery route: `/api/content/article`\nis a 404. Both IDs are set on the model ([Modelling](modelling.md#kinds-of-definitions)). The admin content API\n(`/api/admin/content/<API ID>`) always uses the singular.\n\nThere is no generated code per model: a model created a minute ago is served by the same routes at once.\nDelivery returns **published** content only; drafts, unpublished entries, private media and fields your token\nmay not read never appear. The [REST reference](reference/rest-api.md) lists every read parameter (app-user\nwrites are described in [End users](end-users.md)); your instance's own OpenAPI document, for its current\nschema, is at `/api/docs` (admins).\n\nThe examples below use the [example site](example-site.md)'s models.\n\n## Tokens\n\nCreate a **delivery role** (Network → Roles → New role, kind _Delivery_) with `read` on the models your site\nneeds, then an API token bound to it (Settings → API tokens). Send it as a bearer token:\n\n```sh\ncurl -H \"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\" \"$SHAPIO_URL/api/content/articles?locale=fr\"\n```\n\n- Delivery tokens can only ever read, whatever their role says.\n- A role's grant covers every field marked `public` (the default); `public: false` fields are hidden unless the\n grant names them.\n- Without a token, a request is _anonymous_: it gets what the built-in **public** app role grants, which is\n nothing until you allow it (Network → Roles → App roles). Use that for content anyone may read from the\n browser. App users' own tokens are covered in [End users](end-users.md).\n\n## Sites\n\nOne Shapio instance can host several [sites](sites.md) that share the content types but each have their own\ncontent, tokens and snapshots. Every delivery request reads exactly one site:\n\n1. **The token's site.** Delivery tokens belong to the site they were created on, and only ever read it.\n2. **The site the request names**, with `?site=<key>` or the `Shapio-Site: <key>` header. Anonymous callers and\n network admin tokens use this to pick a site.\n3. **The primary site**, when neither names one. An instance with a single site never needs to name it.\n\nNaming a different site than the token's is refused with `403 SITE_MISMATCH`, never redirected, and so is a\nrequest whose header and `?site=` disagree. An unknown key is `404 SITE_NOT_FOUND`. Entries of another site\nread as not found, and relations never cross sites.\n\n```sh\ncurl \"$SHAPIO_URL/api/content/articles?site=marketing\"\n```\n\nAnonymous reads get what the app roles bound to the request site's `public` audience grant. The primary site\nbinds the built-in **public** role; a new site binds none, so it serves nothing anonymously until you bind one\n([Sites](sites.md#app-users-and-anonymous-access)).\n\nWith `@shapio/client`, pass the site once:\n\n```ts\nconst shapio = createClient({ baseUrl: process.env.SHAPIO_URL, token, site: 'marketing' });\n```\n\nThe client sends it as `?site=` on delivery and snapshot reads, which keeps a cross-origin `GET` free of a\nCORS preflight and keeps URL-keyed caches apart. Every other request (writes, GraphQL, the admin API) carries\nthe `Shapio-Site` header. Leave `site` out to read the token's site, or the primary site.\n\n## Responses\n\n```json\n{\n \"data\": [\n {\n \"id\": \"6f2c…\",\n \"locale\": \"fr\",\n \"createdAt\": \"2026-10-01T09:12:44.512Z\",\n \"updatedAt\": \"2026-10-01T09:30:02.104Z\",\n \"publishedAt\": \"2026-10-01T09:30:02.104Z\",\n \"title\": \"Modéliser du contenu sans déploiement\",\n \"slug\": \"modelling-without-a-deploy\",\n \"excerpt\": \"…\",\n \"body\": {\n \"format\": \"shapio-richtext\",\n \"version\": 1,\n \"doc\": { \"type\": \"doc\", \"content\": [] },\n \"html\": \"<p>…</p>\"\n },\n \"cover\": { \"id\": \"…\", \"url\": \"…\", \"width\": 1600, \"height\": 900, \"alt\": \"…\", \"variants\": [] },\n \"author\": \"0b7e…\",\n \"publishedOn\": \"2026-09-01\"\n }\n ],\n \"meta\": {\n \"locale\": \"fr\",\n \"snapshot\": 10,\n \"pagination\": { \"page\": 1, \"pageSize\": 25, \"total\": 2, \"pageCount\": 1 }\n }\n}\n```\n\n- Entries are flat: system attributes, then every readable field by API ID, `null` (or `[]`) when empty.\n- **Rich text** is the stored JSON document plus `html`, rendered on the server from the JSON with an allow-list\n sanitiser (safe link protocols only, images resolved through the media library).\n- **Media** fields are asset objects with URLs and ready [variants](media.md#image-variants); private assets\n carry an expiring signed URL.\n- **Relations** are target IDs unless you `populate` them. A target that is not published, or that your token\n may not read, is left out (never its ID).\n- **Components** are objects; **dynamic zones** are arrays of objects with `__component` (the component's\n API ID).\n- A single type answers `/api/content/<API ID>` with `{ data: {…}, meta }`.\n\nErrors always look like `{ \"error\": { \"code\": \"…\", \"message\": \"…\", \"details\": … } }`: 400 for an invalid query,\n401 without credentials for content that needs them, 403 when your role may not read the model, 404 for an\nunknown model or entry.\n\n## Query parameters\n\n| Parameter | Example | Notes |\n| ------------------ | ------------------------------------- | --------------------------------------------------------------------------------- |\n| `locale` | `locale=fr` | falls back along the locale chain ([Localization](localization.md)) |\n| `filters` | `filters[slug][$eq]=about` | see below |\n| `sort` | `sort=publishedOn:desc,createdAt:asc` | fields marked sortable, `id`, `createdAt`, `updatedAt` |\n| `page`, `pageSize` | `page=2&pageSize=50` | `pageSize` 25 by default, at most 100 |\n| `fields` | `fields=title,slug` | top-level fields to return (system attributes always come) |\n| `populate` | `populate=author` | relation paths: `author`, `author,tags.author`, or `*`; at most 3 levels |\n| `q` | `q=snapshot` | searches the title field chosen in the model's display settings (400 without one) |\n| `snapshot` | `snapshot=10` | read as of a publication snapshot (below) |\n\n### Filters\n\n`filters[<field>][<operator>]=<value>`, combined with `$and`, `$or` and `$not`:\n\n```sh\ncurl -G \"$SHAPIO_URL/api/content/articles\" -H \"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\" \\\n --data-urlencode 'filters[publishedOn][$gte]=2026-09-10' \\\n --data-urlencode 'filters[$or][0][slug][$eq]=why-builds-pin-a-snapshot' \\\n --data-urlencode 'filters[$or][1][slug][$eq]=modelling-without-a-deploy'\n```\n\n| Operators | Field types |\n| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| `$eq`, `$ne`, `$in`, `$nin`, `$null`, `$notNull` | text, numbers, dates, enums, relations and media (booleans: `$eq`, `$ne`, `$null`, `$notNull`); on lists (`many` relations, multiple media/enums) `$eq` means \"contains\" |\n| `$lt`, `$lte`, `$gt`, `$gte` | text, numbers, dates and times, on fields marked **filterable** or **sortable** |\n| `$contains`, `$notContains`, `$containsi`, `$startsWith`, `$endsWith` | text fields marked **filterable** |\n\n`id`, `createdAt` and `updatedAt` can be filtered too (`publishedAt` is returned but cannot be filtered or\nsorted). JSON, rich text, component and dynamic zone fields cannot be filtered. `$in` takes repeated values or `a,b`. Values are read\nlike stored values, so `2026-10-01T10:00:00+02:00` matches `2026-10-01T08:00:00.000Z`. Unknown fields,\noperators a type does not support, and filters or sorts on fields your token may not read are refused (400/403)\nrather than ignored, so a filter can never reveal a hidden value.\n\n## Snapshots: one consistent moment\n\nEvery publish moves a global **publication snapshot** number forward; every delivery response reports the\none it read in `meta.snapshot`. Pass `snapshot=N` and Shapio answers exactly as it would have at that moment,\neven if more was published since:\n\n```sh\ncurl -H \"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\" \"$SHAPIO_URL/api/content/pages?snapshot=10&locale=en\"\n```\n\nA static site build should read the current snapshot once at the start and pass it with every request: then\na publish in the middle of the build cannot produce a site that mixes two moments. The\n[example site](example-site.md) does exactly this, and Shapio's deployment triggers carry the snapshot to build.\n\nOld snapshots are read through the current schema (a value stored under an earlier field type comes back as\n`null`). A [change set](change-sets.md) goes live as one snapshot, schema and entries together, so a pinned\nbuild sees all of it or none of it.\n\nTwo endpoints serve builds, with the same tokens as `/api/content` and only for models the token may read:\n\n| Endpoint | Answer |\n| ------------------------------------------------ | ------------------------------------------------------------------------ |\n| `GET /api/snapshots/current` | `{ snapshot, schemaVersion, publishedAt }`: what an unpinned read serves |\n| `GET /api/snapshots/changes?from&to&after&limit` | entries and locales whose live content changed between the two snapshots |\n\nDetails, the change classification and incremental-build recipes are in\n[Snapshots and the changes API](snapshots.md).\n\n## Caching\n\nResponses carry a strong `ETag` over the exact body and `Vary: Authorization, Cookie, Shapio-Site`. Send\n`If-None-Match` to get `304 Not Modified` when nothing changed. Anonymous responses are `Cache-Control: public,\nmax-age=0, must-revalidate`; authenticated ones `private`. A CDN that keys its cache on the URL alone and\nignores `Vary` must be given the site as `?site=`, not as the header, so that two sites never share a cached\nresponse.\n\n## Writes\n\nThe same routes accept `POST`, `PUT` and `DELETE` from app users whose roles allow it (for example, members\nediting their own entries). Delivery tokens cannot write. See [End users](end-users.md). Editors and your\nbuild tools use the admin API (`/api/admin/content/<key>`) with admin credentials.\n";
|
|
79
|
+
//#endregion
|
|
80
|
+
//#region src/resources.ts
|
|
81
|
+
const SCHEMA_URI_TEMPLATE = "shapio://schema/{apiKey}";
|
|
82
|
+
const DELIVERY_DOC_URI = "shapio://docs/delivery-api";
|
|
83
|
+
/** Each definition in the pull format (`shapio schema pull`'s files), and the delivery API guide. */
|
|
84
|
+
const registerResources = ({ server, client }) => {
|
|
85
|
+
server.registerResource("schema", new ResourceTemplate(SCHEMA_URI_TEMPLATE, { list: async () => {
|
|
86
|
+
return { resources: (await readSchema(client)).definitions.map(({ definition }) => ({
|
|
87
|
+
uri: `shapio://schema/${definition.apiKey}`,
|
|
88
|
+
name: definition.apiKey,
|
|
89
|
+
title: definition.label,
|
|
90
|
+
mimeType: "application/json"
|
|
91
|
+
})) };
|
|
92
|
+
} }), {
|
|
93
|
+
title: "Content type definition",
|
|
94
|
+
description: "A model or component in the schema file format, with stable IDs.",
|
|
95
|
+
mimeType: "application/json"
|
|
96
|
+
}, async (uri, variables) => {
|
|
97
|
+
const apiKey = String(variables.apiKey);
|
|
98
|
+
const { definition } = findDefinition(await readSchema(client), apiKey);
|
|
99
|
+
return { contents: [{
|
|
100
|
+
uri: uri.href,
|
|
101
|
+
mimeType: "application/json",
|
|
102
|
+
text: serializeDefinition(definition)
|
|
103
|
+
}] };
|
|
104
|
+
});
|
|
105
|
+
server.registerResource("delivery-api", DELIVERY_DOC_URI, {
|
|
106
|
+
title: "Delivery API guide",
|
|
107
|
+
description: "How sites and apps read published content: routes, filters, locales, snapshots, tokens.",
|
|
108
|
+
mimeType: "text/markdown"
|
|
109
|
+
}, (uri) => ({ contents: [{
|
|
110
|
+
uri: uri.href,
|
|
111
|
+
mimeType: "text/markdown",
|
|
112
|
+
text: DELIVERY_API_DOC
|
|
113
|
+
}] }));
|
|
114
|
+
};
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/tools/results.ts
|
|
117
|
+
/** A tool's answer: the API response as pretty JSON text (what agents read best). */
|
|
118
|
+
const jsonResult = (value) => ({ content: [{
|
|
119
|
+
type: "text",
|
|
120
|
+
text: JSON.stringify(value ?? null, null, 2)
|
|
121
|
+
}] });
|
|
122
|
+
/**
|
|
123
|
+
* A refusal or failure the agent should see and act on (a stale version, a missing permission, validation
|
|
124
|
+
* issues), with Shapio's error code and details. Never thrown: the MCP client gets `isError`.
|
|
125
|
+
*/
|
|
126
|
+
const errorResult = (error) => {
|
|
127
|
+
const body = error instanceof ShapioApiError ? {
|
|
128
|
+
status: error.status,
|
|
129
|
+
code: error.code,
|
|
130
|
+
message: error.message,
|
|
131
|
+
details: error.details
|
|
132
|
+
} : {
|
|
133
|
+
code: "TOOL_FAILED",
|
|
134
|
+
message: error instanceof Error ? error.message : String(error)
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
isError: true,
|
|
138
|
+
content: [{
|
|
139
|
+
type: "text",
|
|
140
|
+
text: JSON.stringify({ error: body }, null, 2)
|
|
141
|
+
}]
|
|
142
|
+
};
|
|
143
|
+
};
|
|
144
|
+
/** Runs a tool body, turning any failure into an error result. */
|
|
145
|
+
const runTool = async (body) => {
|
|
146
|
+
try {
|
|
147
|
+
return jsonResult(await body());
|
|
148
|
+
} catch (error) {
|
|
149
|
+
return errorResult(error);
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
//#endregion
|
|
153
|
+
//#region src/tools/changeSets.ts
|
|
154
|
+
const SET_ID = z.string().min(1).describe("Change set ID");
|
|
155
|
+
/**
|
|
156
|
+
* Change sets: the reviewable bundle of schema drafts and entry publications that ships as one snapshot.
|
|
157
|
+
* Agents create and fill them; shipping is a person's call (`change_sets_ship` exists only with
|
|
158
|
+
* --allow-ship, and the server also needs the token's role to hold changes.ship).
|
|
159
|
+
*/
|
|
160
|
+
const registerChangeSetTools = ({ server, client, options }) => {
|
|
161
|
+
server.registerTool("change_sets_list", {
|
|
162
|
+
title: "List change sets",
|
|
163
|
+
description: "Change sets, newest first (every status but discarded unless status is given).",
|
|
164
|
+
inputSchema: z.object({
|
|
165
|
+
status: z.string().optional().describe("Comma-separated: open, scheduled, shipping, shipped, failed, discarded"),
|
|
166
|
+
cursor: z.string().optional(),
|
|
167
|
+
limit: z.number().int().positive().max(100).optional()
|
|
168
|
+
}),
|
|
169
|
+
annotations: {
|
|
170
|
+
readOnlyHint: true,
|
|
171
|
+
openWorldHint: false
|
|
172
|
+
}
|
|
173
|
+
}, (query) => runTool(() => client.admin.changeSets.list(query)));
|
|
174
|
+
server.registerTool("change_sets_create", {
|
|
175
|
+
title: "Create a change set",
|
|
176
|
+
description: "An empty, open change set to collect schema drafts and entry publications for review.",
|
|
177
|
+
inputSchema: z.object({
|
|
178
|
+
title: z.string().min(1).max(200),
|
|
179
|
+
description: z.string().max(5e3).optional()
|
|
180
|
+
}),
|
|
181
|
+
annotations: {
|
|
182
|
+
destructiveHint: false,
|
|
183
|
+
openWorldHint: false
|
|
184
|
+
}
|
|
185
|
+
}, ({ title, description }) => runTool(() => client.admin.changeSets.create({
|
|
186
|
+
title,
|
|
187
|
+
...description ? { description } : {}
|
|
188
|
+
})));
|
|
189
|
+
server.registerTool("change_sets_add_entry", {
|
|
190
|
+
title: "Add an entry to a change set",
|
|
191
|
+
description: "Proposes publishing (or unpublishing) one entry locale when the set ships. The entry's current draft is what ships; the review shows the field diff against what is live.",
|
|
192
|
+
inputSchema: z.object({
|
|
193
|
+
changeSetId: SET_ID,
|
|
194
|
+
model: z.string().min(1).describe("The model's API ID"),
|
|
195
|
+
entryId: z.string().min(1),
|
|
196
|
+
locale: z.string().optional().describe("Omit for non-localized models and the default locale"),
|
|
197
|
+
action: z.enum(["publish", "unpublish"]).default("publish")
|
|
198
|
+
}),
|
|
199
|
+
annotations: {
|
|
200
|
+
destructiveHint: false,
|
|
201
|
+
openWorldHint: false
|
|
202
|
+
}
|
|
203
|
+
}, ({ changeSetId, model, entryId, locale, action }) => runTool(() => client.admin.changeSets.addEntry(changeSetId, {
|
|
204
|
+
modelKey: model,
|
|
205
|
+
entryId,
|
|
206
|
+
action,
|
|
207
|
+
...locale ? { locale } : {}
|
|
208
|
+
})));
|
|
209
|
+
server.registerTool("change_sets_review", {
|
|
210
|
+
title: "Review a change set",
|
|
211
|
+
description: "The set (status, version, items) and its review: field diffs per entry, the schema plan per draft (breaking, destructive, conversions), blocking issues, warnings and the consumers of affected fields.",
|
|
212
|
+
inputSchema: z.object({ changeSetId: SET_ID }),
|
|
213
|
+
annotations: {
|
|
214
|
+
readOnlyHint: true,
|
|
215
|
+
openWorldHint: false
|
|
216
|
+
}
|
|
217
|
+
}, ({ changeSetId }) => runTool(async () => {
|
|
218
|
+
const [set, review] = await Promise.all([client.admin.changeSets.get(changeSetId), client.admin.changeSets.review(changeSetId)]);
|
|
219
|
+
return {
|
|
220
|
+
set,
|
|
221
|
+
review
|
|
222
|
+
};
|
|
223
|
+
}));
|
|
224
|
+
if (options.allowShip) server.registerTool("change_sets_ship", {
|
|
225
|
+
title: "Ship a change set",
|
|
226
|
+
description: "Makes the set live as one snapshot. Only when the person you work for asked for it. expectedVersion is the set version change_sets_review showed; breaking or destructive schema changes need the acknowledgement. Refused when the token's role lacks changes.ship.",
|
|
227
|
+
inputSchema: z.object({
|
|
228
|
+
changeSetId: SET_ID,
|
|
229
|
+
expectedVersion: z.number().int().nonnegative(),
|
|
230
|
+
acknowledgeBreaking: z.boolean().optional(),
|
|
231
|
+
acknowledgeDestructive: z.boolean().optional()
|
|
232
|
+
}),
|
|
233
|
+
annotations: {
|
|
234
|
+
destructiveHint: true,
|
|
235
|
+
openWorldHint: false
|
|
236
|
+
}
|
|
237
|
+
}, ({ changeSetId, ...body }) => runTool(() => client.admin.changeSets.ship(changeSetId, body)));
|
|
238
|
+
};
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/tools/content.ts
|
|
241
|
+
const MODEL = z.string().min(1).describe("The model's API ID (singular, e.g. \"article\")");
|
|
242
|
+
const LOCALE = z.string().min(1).optional().describe("Locale code; the default locale when omitted");
|
|
243
|
+
const PUBLISHED = z.boolean().optional().describe("Read published content through the delivery API instead of drafts (implied by snapshot)");
|
|
244
|
+
const SNAPSHOT = z.number().int().nonnegative().optional().describe("Read published content as of publication snapshot N");
|
|
245
|
+
const QUERY = z.object({
|
|
246
|
+
model: MODEL,
|
|
247
|
+
filters: z.record(z.string(), z.unknown()).optional().describe("Filter tree by field API ID, e.g. { \"title\": { \"$containsi\": \"launch\" } }; $and/$or take lists"),
|
|
248
|
+
sort: z.array(z.object({
|
|
249
|
+
field: z.string().min(1),
|
|
250
|
+
direction: z.enum(["asc", "desc"])
|
|
251
|
+
})).optional(),
|
|
252
|
+
page: z.number().int().positive().optional(),
|
|
253
|
+
pageSize: z.number().int().positive().max(100).optional(),
|
|
254
|
+
q: z.string().optional().describe("Free-text search over the title field"),
|
|
255
|
+
locale: LOCALE,
|
|
256
|
+
fields: z.array(z.string()).optional().describe("Top-level fields to return"),
|
|
257
|
+
populate: z.array(z.string()).optional().describe("Relation paths to expand, e.g. \"author\""),
|
|
258
|
+
status: z.enum([
|
|
259
|
+
"draft",
|
|
260
|
+
"published",
|
|
261
|
+
"modified"
|
|
262
|
+
]).optional().describe("Drafts only: entries in this status"),
|
|
263
|
+
published: PUBLISHED,
|
|
264
|
+
snapshot: SNAPSHOT
|
|
265
|
+
});
|
|
266
|
+
const DATA = z.record(z.string(), z.unknown()).describe("Field values by API ID. Rich text is Shapio's JSON document format, never HTML.");
|
|
267
|
+
/** Entries: query and read (drafts or published), create and update drafts. Never publishes. */
|
|
268
|
+
const registerContentTools = ({ server, client }) => {
|
|
269
|
+
server.registerTool("content_query", {
|
|
270
|
+
title: "Query entries",
|
|
271
|
+
description: "A page of a model's entries. Drafts by default (what editors see); published=true or snapshot=N reads what the delivery API serves.",
|
|
272
|
+
inputSchema: QUERY,
|
|
273
|
+
annotations: {
|
|
274
|
+
readOnlyHint: true,
|
|
275
|
+
openWorldHint: false
|
|
276
|
+
}
|
|
277
|
+
}, ({ model, published, snapshot, status, filters, sort, ...rest }) => runTool(async () => {
|
|
278
|
+
const query = {
|
|
279
|
+
...rest,
|
|
280
|
+
...filters ? { filters } : {},
|
|
281
|
+
...sort ? { sort } : {}
|
|
282
|
+
};
|
|
283
|
+
if (published || snapshot !== void 0) {
|
|
284
|
+
const { definition } = findDefinition(await readSchema(client), model);
|
|
285
|
+
const routeKey = routeKeyOf$1(definition);
|
|
286
|
+
return definition.kind === "singleton" ? client.delivery.singleton(routeKey, {
|
|
287
|
+
...rest.locale ? { locale: rest.locale } : {},
|
|
288
|
+
...snapshot !== void 0 ? { snapshot } : {}
|
|
289
|
+
}) : client.delivery.list(routeKey, {
|
|
290
|
+
...query,
|
|
291
|
+
...snapshot !== void 0 ? { snapshot } : {}
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
return client.admin.content.list(model, {
|
|
295
|
+
...query,
|
|
296
|
+
...status ? { status } : {}
|
|
297
|
+
});
|
|
298
|
+
}));
|
|
299
|
+
server.registerTool("content_get", {
|
|
300
|
+
title: "Read an entry",
|
|
301
|
+
description: "One entry: its draft with every locale's status and version (send version back as expectedVersion to content_update), or the published version when published=true or snapshot=N.",
|
|
302
|
+
inputSchema: z.object({
|
|
303
|
+
model: MODEL,
|
|
304
|
+
id: z.string().min(1),
|
|
305
|
+
locale: LOCALE,
|
|
306
|
+
published: PUBLISHED,
|
|
307
|
+
snapshot: SNAPSHOT
|
|
308
|
+
}),
|
|
309
|
+
annotations: {
|
|
310
|
+
readOnlyHint: true,
|
|
311
|
+
openWorldHint: false
|
|
312
|
+
}
|
|
313
|
+
}, ({ model, id, locale, published, snapshot }) => runTool(async () => {
|
|
314
|
+
if (published || snapshot !== void 0) {
|
|
315
|
+
const { definition } = findDefinition(await readSchema(client), model);
|
|
316
|
+
return client.delivery.get(routeKeyOf$1(definition), id, {
|
|
317
|
+
...locale ? { locale } : {},
|
|
318
|
+
...snapshot !== void 0 ? { snapshot } : {}
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
return client.admin.content.get(model, id, locale ? { locale } : {});
|
|
322
|
+
}));
|
|
323
|
+
server.registerTool("content_create", {
|
|
324
|
+
title: "Create a draft entry",
|
|
325
|
+
description: "Creates an entry as a draft (never published). Validated by the server against the live model. Add it to a change set with change_sets_add_entry to propose publishing it.",
|
|
326
|
+
inputSchema: z.object({
|
|
327
|
+
model: MODEL,
|
|
328
|
+
data: DATA,
|
|
329
|
+
locale: LOCALE
|
|
330
|
+
}),
|
|
331
|
+
annotations: {
|
|
332
|
+
destructiveHint: false,
|
|
333
|
+
openWorldHint: false
|
|
334
|
+
}
|
|
335
|
+
}, ({ model, data, locale }) => runTool(() => client.admin.content.create(model, {
|
|
336
|
+
data,
|
|
337
|
+
...locale ? { locale } : {}
|
|
338
|
+
})));
|
|
339
|
+
server.registerTool("content_update", {
|
|
340
|
+
title: "Update a draft entry",
|
|
341
|
+
description: "Saves changed fields into one locale's draft (absent fields are kept, null clears). expectedVersion is the version content_get returned; a stale one is refused (CONTENT_VERSION_CONFLICT): read again and redo. Pass expectedVersion null to start a new locale of the entry.",
|
|
342
|
+
inputSchema: z.object({
|
|
343
|
+
model: MODEL,
|
|
344
|
+
id: z.string().min(1),
|
|
345
|
+
data: DATA,
|
|
346
|
+
expectedVersion: z.number().int().nonnegative().nullable(),
|
|
347
|
+
locale: LOCALE
|
|
348
|
+
}),
|
|
349
|
+
annotations: {
|
|
350
|
+
destructiveHint: false,
|
|
351
|
+
idempotentHint: false,
|
|
352
|
+
openWorldHint: false
|
|
353
|
+
}
|
|
354
|
+
}, ({ model, id, data, expectedVersion, locale }) => runTool(() => client.admin.content.update(model, id, {
|
|
355
|
+
data,
|
|
356
|
+
expectedVersion,
|
|
357
|
+
...locale ? { locale } : {}
|
|
358
|
+
})));
|
|
359
|
+
};
|
|
360
|
+
//#endregion
|
|
361
|
+
//#region src/tools/insights.ts
|
|
362
|
+
/** Checks and signals: pre-flight for one entry, content health findings, field usage by consumers. */
|
|
363
|
+
const registerInsightTools = ({ server, client }) => {
|
|
364
|
+
server.registerTool("preflight_run", {
|
|
365
|
+
title: "Pre-flight an entry",
|
|
366
|
+
description: "What publishing these locales of an entry would run into (validation, missing locales, references, alt text), without publishing anything.",
|
|
367
|
+
inputSchema: z.object({
|
|
368
|
+
model: z.string().min(1).describe("The model's API ID"),
|
|
369
|
+
id: z.string().min(1),
|
|
370
|
+
locales: z.array(z.string()).optional()
|
|
371
|
+
}),
|
|
372
|
+
annotations: {
|
|
373
|
+
readOnlyHint: true,
|
|
374
|
+
openWorldHint: false
|
|
375
|
+
}
|
|
376
|
+
}, ({ model, id, locales }) => runTool(() => client.admin.preflight.run(model, id, locales ? { locales } : {})));
|
|
377
|
+
server.registerTool("health_list", {
|
|
378
|
+
title: "List content health findings",
|
|
379
|
+
description: `Open findings of the content health rules (${HEALTH_RULES.join(", ")}), by rule and model.`,
|
|
380
|
+
inputSchema: z.object({
|
|
381
|
+
rule: z.enum(HEALTH_RULES).optional(),
|
|
382
|
+
model: z.string().optional().describe("The model's API ID"),
|
|
383
|
+
cursor: z.string().optional(),
|
|
384
|
+
limit: z.number().int().positive().max(100).optional()
|
|
385
|
+
}),
|
|
386
|
+
annotations: {
|
|
387
|
+
readOnlyHint: true,
|
|
388
|
+
openWorldHint: false
|
|
389
|
+
}
|
|
390
|
+
}, ({ model, ...query }) => runTool(() => client.admin.contentHealth.list({
|
|
391
|
+
...query,
|
|
392
|
+
...model ? { modelKey: model } : {}
|
|
393
|
+
})));
|
|
394
|
+
server.registerTool("usage_fields", {
|
|
395
|
+
title: "Field usage",
|
|
396
|
+
description: "Which fields of a model sites and apps read, per API token, over the last N days: check before renaming or removing a field.",
|
|
397
|
+
inputSchema: z.object({
|
|
398
|
+
model: z.string().min(1).describe("The model's API ID"),
|
|
399
|
+
days: z.number().int().positive().max(365).optional()
|
|
400
|
+
}),
|
|
401
|
+
annotations: {
|
|
402
|
+
readOnlyHint: true,
|
|
403
|
+
openWorldHint: false
|
|
404
|
+
}
|
|
405
|
+
}, ({ model, days }) => runTool(async () => {
|
|
406
|
+
const { definition } = findDefinition(await readSchema(client), model);
|
|
407
|
+
return client.admin.usage.fields({
|
|
408
|
+
modelId: definition.id,
|
|
409
|
+
...days ? { days } : {}
|
|
410
|
+
});
|
|
411
|
+
}));
|
|
412
|
+
};
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/tools/media.ts
|
|
415
|
+
/**
|
|
416
|
+
* The file a `media_upload` may read: inside the media root after resolving symlinks, so an agent (or text
|
|
417
|
+
* injected into what it reads) cannot have the server read ~/.ssh or anything else outside the project.
|
|
418
|
+
*/
|
|
419
|
+
const resolveMediaPath = async (mediaRoot, path) => {
|
|
420
|
+
const root = await realpath(mediaRoot);
|
|
421
|
+
const target = await realpath(resolve(root, path)).catch(() => {
|
|
422
|
+
throw new Error(`No file at ${path} (relative to the media root ${root})`);
|
|
423
|
+
});
|
|
424
|
+
const inside = relative(root, target);
|
|
425
|
+
if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) throw new Error(`media_upload only reads files under the media root (${root}); start the server with --media-root to change it`);
|
|
426
|
+
return target;
|
|
427
|
+
};
|
|
428
|
+
/** The media library: browse, and upload files from the media root. */
|
|
429
|
+
const registerMediaTools = ({ server, client, options }) => {
|
|
430
|
+
server.registerTool("media_list", {
|
|
431
|
+
title: "List media",
|
|
432
|
+
description: "A page of media assets (ID, filename, type, alt text, visibility, URLs), newest first.",
|
|
433
|
+
inputSchema: z.object({
|
|
434
|
+
folder: z.string().optional().describe("A folder ID, or \"root\" for assets in no folder"),
|
|
435
|
+
mimeType: z.string().optional().describe("\"image/png\" or \"image/*\""),
|
|
436
|
+
search: z.string().optional(),
|
|
437
|
+
cursor: z.string().optional().describe("nextCursor of the previous page"),
|
|
438
|
+
limit: z.number().int().positive().max(100).optional()
|
|
439
|
+
}),
|
|
440
|
+
annotations: {
|
|
441
|
+
readOnlyHint: true,
|
|
442
|
+
openWorldHint: false
|
|
443
|
+
}
|
|
444
|
+
}, (query) => runTool(() => client.admin.media.assets.list(query)));
|
|
445
|
+
server.registerTool("media_upload", {
|
|
446
|
+
title: "Upload a file",
|
|
447
|
+
description: `Uploads a local file into the media library and returns the asset (use its ID in media fields). Only files under ${options.mediaRoot} can be read. Media is stored at once (it is not part of change sets).`,
|
|
448
|
+
inputSchema: z.object({
|
|
449
|
+
path: z.string().min(1).describe("Path relative to the media root (or absolute, inside it)"),
|
|
450
|
+
alt: z.string().max(1e3).optional().describe("Alt text for images"),
|
|
451
|
+
mimeType: z.string().optional().describe("Needed when the extension is not a common one"),
|
|
452
|
+
folderId: z.string().optional(),
|
|
453
|
+
visibility: z.enum(["public", "private"]).optional()
|
|
454
|
+
}),
|
|
455
|
+
annotations: {
|
|
456
|
+
destructiveHint: false,
|
|
457
|
+
openWorldHint: false
|
|
458
|
+
}
|
|
459
|
+
}, ({ path, alt, mimeType, folderId, visibility }) => runTool(async () => {
|
|
460
|
+
const file = await resolveMediaPath(options.mediaRoot, path);
|
|
461
|
+
const asset = await uploadFile(client, {
|
|
462
|
+
baseUrl: options.baseUrl,
|
|
463
|
+
path: file,
|
|
464
|
+
...mimeType ? { mimeType } : {},
|
|
465
|
+
...folderId ? { folderId } : {},
|
|
466
|
+
...visibility ? { visibility } : {}
|
|
467
|
+
});
|
|
468
|
+
return alt ? client.admin.media.assets.update(asset.id, {
|
|
469
|
+
expectedVersion: asset.version,
|
|
470
|
+
alt
|
|
471
|
+
}) : asset;
|
|
472
|
+
}));
|
|
473
|
+
};
|
|
474
|
+
//#endregion
|
|
475
|
+
//#region src/schemaDrafts.ts
|
|
476
|
+
const schemaItemsOf = (set) => set.items.filter((item) => item.kind === "schema");
|
|
477
|
+
/**
|
|
478
|
+
* Relation targets and component references are stable IDs. Agents think in API IDs, so a reference that
|
|
479
|
+
* is not an ID is looked up among the active definitions and the set's drafts (and this definition itself,
|
|
480
|
+
* for a self-relation); anything unknown is left for the server to report.
|
|
481
|
+
*/
|
|
482
|
+
const resolveReferences = (definition, idsByApiKey) => {
|
|
483
|
+
const resolve = (value) => typeof value === "string" && !isStableId(value) ? idsByApiKey.get(value) ?? value : value;
|
|
484
|
+
const fields = Array.isArray(definition.fields) ? definition.fields : [];
|
|
485
|
+
return {
|
|
486
|
+
...definition,
|
|
487
|
+
fields: fields.map((field) => {
|
|
488
|
+
const settings = field.settings;
|
|
489
|
+
if (!settings) return field;
|
|
490
|
+
if (field.type === "relation") return {
|
|
491
|
+
...field,
|
|
492
|
+
settings: {
|
|
493
|
+
...settings,
|
|
494
|
+
target: resolve(settings.target)
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
if (field.type === "component") return {
|
|
498
|
+
...field,
|
|
499
|
+
settings: {
|
|
500
|
+
...settings,
|
|
501
|
+
component: resolve(settings.component)
|
|
502
|
+
}
|
|
503
|
+
};
|
|
504
|
+
if (field.type === "dynamiczone" && Array.isArray(settings.components)) return {
|
|
505
|
+
...field,
|
|
506
|
+
settings: {
|
|
507
|
+
...settings,
|
|
508
|
+
components: settings.components.map(resolve)
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
return field;
|
|
512
|
+
})
|
|
513
|
+
};
|
|
514
|
+
};
|
|
515
|
+
/**
|
|
516
|
+
* Puts a definition into a change set as a draft: picks its stable ID (the active definition's, the set's
|
|
517
|
+
* existing draft's, or a new one), its base version and the draft version to replace, then lets the server
|
|
518
|
+
* parse, validate and plan it. Nothing goes live until a person ships the set.
|
|
519
|
+
*/
|
|
520
|
+
const putDefinitionDraft = async (client, changeSetId, definition) => {
|
|
521
|
+
if (typeof definition.apiKey !== "string" || typeof definition.kind !== "string") throw new Error("A definition needs at least \"kind\" (collection, singleton or component) and \"apiKey\"");
|
|
522
|
+
const [schema, set] = await Promise.all([readSchema(client), client.admin.changeSets.get(changeSetId)]);
|
|
523
|
+
const drafts = schemaItemsOf(set);
|
|
524
|
+
const apiKey = definition.apiKey;
|
|
525
|
+
const explicitId = typeof definition.id === "string" ? definition.id : void 0;
|
|
526
|
+
const active = schema.definitions.find(({ definition: candidate }) => candidate.id === explicitId || !explicitId && candidate.apiKey === apiKey);
|
|
527
|
+
const drafted = drafts.find((item) => item.definitionId === explicitId || !explicitId && item.apiKey === apiKey);
|
|
528
|
+
const id = explicitId ?? active?.definition.id ?? drafted?.definitionId ?? randomUUID();
|
|
529
|
+
const idsByApiKey = new Map([
|
|
530
|
+
...schema.definitions.map(({ definition: candidate }) => [candidate.apiKey, candidate.id]),
|
|
531
|
+
...drafts.map((item) => [item.apiKey, item.definitionId]),
|
|
532
|
+
[apiKey, id]
|
|
533
|
+
]);
|
|
534
|
+
const payload = resolveReferences({
|
|
535
|
+
...definition,
|
|
536
|
+
id
|
|
537
|
+
}, idsByApiKey);
|
|
538
|
+
const draft = await client.admin.changeSets.putSchemaDraft(changeSetId, id, {
|
|
539
|
+
category: definition.kind === "component" ? "component" : "model",
|
|
540
|
+
definition: payload,
|
|
541
|
+
baseVersion: active?.version ?? null,
|
|
542
|
+
...drafted ? { expectedDraftVersion: drafted.draftVersion } : {}
|
|
543
|
+
});
|
|
544
|
+
return {
|
|
545
|
+
changeSetId,
|
|
546
|
+
definitionId: id,
|
|
547
|
+
operation: draft.operation,
|
|
548
|
+
draftVersion: draft.version,
|
|
549
|
+
draft
|
|
550
|
+
};
|
|
551
|
+
};
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region src/tools/schema.ts
|
|
554
|
+
const READ_ONLY = {
|
|
555
|
+
readOnlyHint: true,
|
|
556
|
+
openWorldHint: false
|
|
557
|
+
};
|
|
558
|
+
const DEFINITION_DESCRIPTION = "A whole definition in Shapio's authored format: { kind: \"collection\" | \"singleton\" | \"component\", apiKey, label, pluralApiKey? (collections), localized?, draftAndPublish?, fields: [{ apiKey, label, type, required?, localized?, settings? }] }. IDs are optional: an existing definition keeps its IDs (matched by API ID). Relation targets and component references may be given as API IDs. Read shapio://schema/{apiKey} to see the format of an existing one.";
|
|
559
|
+
/** The schema: list and read definitions, and draft changes into a change set (never activated here). */
|
|
560
|
+
const registerSchemaTools = ({ server, client }) => {
|
|
561
|
+
server.registerTool("schema_list", {
|
|
562
|
+
title: "List content types",
|
|
563
|
+
description: "Every model (collection, singleton) and component with its API IDs, version and fields (types only). Delivery reads use pluralApiKey for collections.",
|
|
564
|
+
inputSchema: z.object({}),
|
|
565
|
+
annotations: READ_ONLY
|
|
566
|
+
}, () => runTool(async () => {
|
|
567
|
+
const schema = await readSchema(client);
|
|
568
|
+
return {
|
|
569
|
+
schemaVersion: schema.schemaVersion,
|
|
570
|
+
definitions: schema.definitions.map(summarize)
|
|
571
|
+
};
|
|
572
|
+
}));
|
|
573
|
+
server.registerTool("schema_get", {
|
|
574
|
+
title: "Read a content type",
|
|
575
|
+
description: "One definition in full (fields with settings), by API ID or stable ID, with its version.",
|
|
576
|
+
inputSchema: z.object({ apiKey: z.string().min(1).describe("API ID (or stable ID) of the definition") }),
|
|
577
|
+
annotations: READ_ONLY
|
|
578
|
+
}, ({ apiKey }) => runTool(async () => findDefinition(await readSchema(client), apiKey)));
|
|
579
|
+
server.registerTool("schema_draft", {
|
|
580
|
+
title: "Draft a content type change",
|
|
581
|
+
description: "Proposes a new or changed definition as a draft in a change set (a new set when changeSetId is omitted). Nothing changes on the live schema until a person reviews and ships the set. Returns the change set ID; read change_sets_review next.",
|
|
582
|
+
inputSchema: z.object({
|
|
583
|
+
definition: z.record(z.string(), z.unknown()).describe(DEFINITION_DESCRIPTION),
|
|
584
|
+
changeSetId: z.string().optional().describe("An open change set; omit to start a new one"),
|
|
585
|
+
title: z.string().min(1).max(200).optional().describe("Title of the new change set")
|
|
586
|
+
}),
|
|
587
|
+
annotations: {
|
|
588
|
+
destructiveHint: false,
|
|
589
|
+
openWorldHint: false
|
|
590
|
+
}
|
|
591
|
+
}, ({ definition, changeSetId, title }) => runTool(async () => {
|
|
592
|
+
const apiKey = typeof definition.apiKey === "string" ? definition.apiKey : "draft";
|
|
593
|
+
const setId = changeSetId ?? (await client.admin.changeSets.create({ title: title ?? `Schema: ${apiKey}` })).id;
|
|
594
|
+
return putDefinitionDraft(client, setId, definition);
|
|
595
|
+
}));
|
|
596
|
+
server.registerTool("change_sets_add_schema_draft", {
|
|
597
|
+
title: "Add a schema draft to a change set",
|
|
598
|
+
description: "Puts a new or changed definition into an existing change set as a draft (replaces this set's earlier draft of the same definition). Ships only when a person ships the set.",
|
|
599
|
+
inputSchema: z.object({
|
|
600
|
+
changeSetId: z.string().min(1),
|
|
601
|
+
definition: z.record(z.string(), z.unknown()).describe(DEFINITION_DESCRIPTION)
|
|
602
|
+
}),
|
|
603
|
+
annotations: {
|
|
604
|
+
destructiveHint: false,
|
|
605
|
+
openWorldHint: false
|
|
606
|
+
}
|
|
607
|
+
}, ({ changeSetId, definition }) => runTool(() => putDefinitionDraft(client, changeSetId, definition)));
|
|
608
|
+
};
|
|
609
|
+
//#endregion
|
|
610
|
+
//#region src/tools/snapshots.ts
|
|
611
|
+
/** Publication snapshots: the ledger, the diff between two, and restore (as a reviewable change set). */
|
|
612
|
+
const registerSnapshotTools = ({ server, client }) => {
|
|
613
|
+
server.registerTool("snapshots_list", {
|
|
614
|
+
title: "List snapshots",
|
|
615
|
+
description: "The publication ledger, newest first: what went live, when, why and by whom.",
|
|
616
|
+
inputSchema: z.object({
|
|
617
|
+
cursor: z.string().optional(),
|
|
618
|
+
limit: z.number().int().positive().max(100).optional()
|
|
619
|
+
}),
|
|
620
|
+
annotations: {
|
|
621
|
+
readOnlyHint: true,
|
|
622
|
+
openWorldHint: false
|
|
623
|
+
}
|
|
624
|
+
}, (query) => runTool(() => client.admin.snapshots.list(query)));
|
|
625
|
+
server.registerTool("snapshots_changes", {
|
|
626
|
+
title: "Changes between snapshots",
|
|
627
|
+
description: "Which entries were published, updated or unpublished between snapshot \"from\" and \"to\" (default: now). Names entries, never values.",
|
|
628
|
+
inputSchema: z.object({
|
|
629
|
+
from: z.number().int().nonnegative(),
|
|
630
|
+
to: z.number().int().nonnegative().optional(),
|
|
631
|
+
after: z.string().optional().describe("nextCursor of the previous page"),
|
|
632
|
+
limit: z.number().int().positive().max(500).optional()
|
|
633
|
+
}),
|
|
634
|
+
annotations: {
|
|
635
|
+
readOnlyHint: true,
|
|
636
|
+
openWorldHint: false
|
|
637
|
+
}
|
|
638
|
+
}, (query) => runTool(() => client.snapshots.changes(query)));
|
|
639
|
+
server.registerTool("snapshots_restore", {
|
|
640
|
+
title: "Propose restoring a snapshot",
|
|
641
|
+
description: "Creates an open change set that would bring live content back to what snapshot N served. Nothing changes until a person ships it; the schema is never rolled back.",
|
|
642
|
+
inputSchema: z.object({ seq: z.number().int().positive() }),
|
|
643
|
+
annotations: {
|
|
644
|
+
destructiveHint: false,
|
|
645
|
+
openWorldHint: false
|
|
646
|
+
}
|
|
647
|
+
}, ({ seq }) => runTool(() => client.admin.snapshots.restore(seq)));
|
|
648
|
+
};
|
|
649
|
+
//#endregion
|
|
650
|
+
//#region src/server.ts
|
|
651
|
+
const MCP_SERVER_NAME = "shapio";
|
|
652
|
+
const MCP_SERVER_VERSION = version;
|
|
653
|
+
const INSTRUCTIONS = "Shapio is a headless CMS whose content types are live data. Agents propose, people ship: draft schema changes and entries, collect them in a change set, and leave shipping to a person. Model and field identifiers are called \"API IDs\". Read shapio://docs/delivery-api for how sites read content.";
|
|
654
|
+
/** The MCP server for one Shapio instance, with every tool, resource and prompt registered. */
|
|
655
|
+
const createShapioMcpServer = (options, client = createClient({
|
|
656
|
+
baseUrl: options.baseUrl,
|
|
657
|
+
token: options.token,
|
|
658
|
+
...options.site !== void 0 ? { site: options.site } : {}
|
|
659
|
+
})) => {
|
|
660
|
+
const server = new McpServer({
|
|
661
|
+
name: MCP_SERVER_NAME,
|
|
662
|
+
version: MCP_SERVER_VERSION
|
|
663
|
+
}, { instructions: INSTRUCTIONS });
|
|
664
|
+
const context = {
|
|
665
|
+
server,
|
|
666
|
+
client,
|
|
667
|
+
options
|
|
668
|
+
};
|
|
669
|
+
registerSchemaTools(context);
|
|
670
|
+
registerContentTools(context);
|
|
671
|
+
registerMediaTools(context);
|
|
672
|
+
registerInsightTools(context);
|
|
673
|
+
registerChangeSetTools(context);
|
|
674
|
+
registerSnapshotTools(context);
|
|
675
|
+
registerResources(context);
|
|
676
|
+
registerPrompts(context);
|
|
677
|
+
return server;
|
|
678
|
+
};
|
|
679
|
+
//#endregion
|
|
680
|
+
//#region src/options.ts
|
|
681
|
+
/** A site key as Shapio creates them (sites are named by key in URLs, `?site=` and config). */
|
|
682
|
+
const SITE_KEY = /^[a-z][a-z0-9-]{0,62}$/;
|
|
683
|
+
const USAGE = `Usage: shapio-mcp [--allow-ship] [--media-root <dir>] [--site <key>]
|
|
684
|
+
|
|
685
|
+
A Model Context Protocol server (stdio) for a Shapio instance.
|
|
686
|
+
|
|
687
|
+
Environment:
|
|
688
|
+
SHAPIO_URL Shapio's base URL, including any BASE_PATH (e.g. https://cms.example.com)
|
|
689
|
+
SHAPIO_TOKEN An admin-scope API token. Give its role no "changes.ship" permission: agents propose
|
|
690
|
+
change sets, people ship them.
|
|
691
|
+
SHAPIO_SITE The site key to work on (multi-site instances); --site overrides it. Default: the
|
|
692
|
+
token's site, else the primary site.
|
|
693
|
+
|
|
694
|
+
Options:
|
|
695
|
+
--allow-ship Offer the change_sets_ship tool (the token's role must also allow changes.ship)
|
|
696
|
+
--media-root <dir> Directory media_upload may read files from (default: the working directory)
|
|
697
|
+
--site <key> The site to work on (overrides SHAPIO_SITE)
|
|
698
|
+
-h, --help Show this help
|
|
699
|
+
`;
|
|
700
|
+
var OptionsError = class extends Error {
|
|
701
|
+
constructor(message) {
|
|
702
|
+
super(message);
|
|
703
|
+
this.name = "OptionsError";
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
/** Reads the command line and environment; throws OptionsError with a message meant for stderr. */
|
|
707
|
+
const parseOptions = (argv, env, cwd) => {
|
|
708
|
+
let parsed;
|
|
709
|
+
try {
|
|
710
|
+
parsed = parseArgs({
|
|
711
|
+
args: [...argv],
|
|
712
|
+
options: {
|
|
713
|
+
"allow-ship": {
|
|
714
|
+
type: "boolean",
|
|
715
|
+
default: false
|
|
716
|
+
},
|
|
717
|
+
"media-root": { type: "string" },
|
|
718
|
+
site: { type: "string" },
|
|
719
|
+
help: {
|
|
720
|
+
type: "boolean",
|
|
721
|
+
short: "h",
|
|
722
|
+
default: false
|
|
723
|
+
}
|
|
724
|
+
},
|
|
725
|
+
strict: true,
|
|
726
|
+
allowPositionals: false
|
|
727
|
+
});
|
|
728
|
+
} catch (error) {
|
|
729
|
+
throw new OptionsError(error instanceof Error ? error.message : String(error));
|
|
730
|
+
}
|
|
731
|
+
if (parsed.values.help) return "help";
|
|
732
|
+
const baseUrl = env.SHAPIO_URL?.trim();
|
|
733
|
+
const token = env.SHAPIO_TOKEN?.trim();
|
|
734
|
+
if (!baseUrl || !/^https?:\/\//.test(baseUrl)) throw new OptionsError("Set SHAPIO_URL to the Shapio base URL (http:// or https://).");
|
|
735
|
+
if (!token) throw new OptionsError("Set SHAPIO_TOKEN to an admin-scope API token.");
|
|
736
|
+
const site = (parsed.values.site ?? env.SHAPIO_SITE)?.trim() || void 0;
|
|
737
|
+
if (site !== void 0 && !SITE_KEY.test(site)) throw new OptionsError(`"${site}" is not a site key (lower case, starting with a letter).`);
|
|
738
|
+
return {
|
|
739
|
+
baseUrl: baseUrl.replace(/\/+$/, ""),
|
|
740
|
+
token,
|
|
741
|
+
allowShip: parsed.values["allow-ship"],
|
|
742
|
+
mediaRoot: resolve(cwd, parsed.values["media-root"] ?? "."),
|
|
743
|
+
...site !== void 0 ? { site } : {}
|
|
744
|
+
};
|
|
745
|
+
};
|
|
746
|
+
//#endregion
|
|
747
|
+
export { MCP_SERVER_VERSION as a, MCP_SERVER_NAME as i, USAGE as n, createShapioMcpServer as o, parseOptions as r, OptionsError as t };
|
|
748
|
+
|
|
749
|
+
//# sourceMappingURL=options-Bc0S3ldO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"options-Bc0S3ldO.js","names":["routeKeyOf","modelRouteKeyOf","routeKeyOf","packageJson.version"],"sources":["../package.json","../src/prompts.ts","../src/definitions.ts","../src/generated/deliveryApiDoc.ts","../src/resources.ts","../src/tools/results.ts","../src/tools/changeSets.ts","../src/tools/content.ts","../src/tools/insights.ts","../src/tools/media.ts","../src/schemaDrafts.ts","../src/tools/schema.ts","../src/tools/snapshots.ts","../src/server.ts","../src/options.ts"],"sourcesContent":["","import { z } from 'zod';\nimport type { ToolContext } from './context.js';\n\nconst userMessage = (text: string) => ({\n messages: [{ role: 'user' as const, content: { type: 'text' as const, text } }],\n});\n\n/** Starting points for the two jobs agents do most: modelling and reviewing a change set. */\nexport const registerPrompts = ({ server }: ToolContext) => {\n server.registerPrompt(\n 'model_content_type',\n {\n title: 'Model a content type for …',\n description: 'Design a content type for something and draft it into a change set for review.',\n argsSchema: z.object({\n subject: z.string().min(1).describe('What the content type is for, e.g. \"a blog\"'),\n }),\n },\n ({ subject }) =>\n userMessage(\n `Model content types in Shapio for ${subject}.\\n\\n` +\n '1. Call schema_list and read the existing types first; reuse or extend them instead of duplicating.\\n' +\n '2. Design the types: API IDs are camelCase GraphQL names, labels are for people; prefer components ' +\n 'for repeated groups and relations for shared entities.\\n' +\n '3. Draft each type with schema_draft (one change set for the whole design: pass the changeSetId ' +\n 'from the first call to the rest).\\n' +\n '4. Read change_sets_review, fix every blocking issue, and summarise the design and the review for ' +\n 'me. Do not ship: I review and ship the change set myself.',\n ),\n );\n\n server.registerPrompt(\n 'review_change_set',\n {\n title: 'Review change set N',\n description: 'Explain what a change set would do when it ships, and what to check first.',\n argsSchema: z.object({ changeSetId: z.string().min(1).describe('The change set ID') }),\n },\n ({ changeSetId }) =>\n userMessage(\n `Review Shapio change set ${changeSetId}. Call change_sets_review and tell me, briefly:\\n` +\n '- what goes live (schema changes and entries, with the field diffs that matter);\\n' +\n '- anything breaking or destructive, and which API consumers read the affected fields ' +\n '(usage_fields);\\n' +\n '- blocking issues and warnings, and how to fix each;\\n' +\n '- whether you would ship it. Do not ship it yourself.',\n ),\n );\n};\n","import type { ShapioClient } from '@shapio/client';\nimport { isModelDefinition, routeKeyOf as modelRouteKeyOf, type SchemaDefinition } from '@shapio/schema';\n\ntype Exported = Awaited<ReturnType<ShapioClient['admin']['schema']['export']>>;\nexport type ExportedDefinition = Exported['definitions'][number];\n\n/** The active schema (the pull format), read fresh for each call: models change live. */\nexport const readSchema = (client: ShapioClient): Promise<Exported> => client.admin.schema.export();\n\n/** An active definition by API ID (or stable ID); throws a message the agent can act on. */\nexport const findDefinition = (schema: Exported, key: string): ExportedDefinition => {\n const found = schema.definitions.find(\n ({ definition }) => definition.apiKey === key || definition.id === key,\n );\n if (!found) {\n const known = schema.definitions.map(({ definition }) => definition.apiKey).join(', ') || '(none)';\n throw new Error(`No model or component with API ID \"${key}\". Known: ${known}`);\n }\n return found;\n};\n\n/**\n * The delivery route key: a collection's plural API ID (`articles`), a singleton's API ID. The admin content\n * API uses the singular API ID instead. Components have no route.\n */\nexport const routeKeyOf = (definition: SchemaDefinition): string => {\n if (!isModelDefinition(definition)) {\n throw new Error(\n `\"${definition.apiKey}\" is a component: components are read through the models that use them`,\n );\n }\n return modelRouteKeyOf(definition);\n};\n\n/** A one-line summary per definition, for listings that should not carry every field's settings. */\nexport const summarize = ({ definition, version }: ExportedDefinition) => ({\n id: definition.id,\n kind: definition.kind,\n apiKey: definition.apiKey,\n ...(definition.kind === 'collection' ? { pluralApiKey: modelRouteKeyOf(definition) } : {}),\n label: definition.label,\n version,\n fields: definition.fields.map((field) => ({\n apiKey: field.apiKey,\n type: field.type,\n required: field.required,\n localized: field.localized,\n })),\n});\n","// Generated by scripts/embedDocs.mjs from documentation/delivery-api.md. Do not edit.\nexport const DELIVERY_API_DOC = \"# Delivery API (REST)\\n\\nYour sites and apps read published content from one generic route per model:\\n\\n```text\\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<plural API ID> # a collection: a page of entries\\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<plural API ID>/<entry id> # a collection: one entry\\nGET {PUBLIC_URL}{BASE_PATH}/api/content/<API ID> # a single type: its entry\\n```\\n\\nA collection is addressed by its **plural API ID** (`/api/content/articles`), a single type by its **API ID**\\n(`/api/content/homepage`). The singular API ID of a collection is not a delivery route: `/api/content/article`\\nis a 404. Both IDs are set on the model ([Modelling](modelling.md#kinds-of-definitions)). The admin content API\\n(`/api/admin/content/<API ID>`) always uses the singular.\\n\\nThere is no generated code per model: a model created a minute ago is served by the same routes at once.\\nDelivery returns **published** content only; drafts, unpublished entries, private media and fields your token\\nmay not read never appear. The [REST reference](reference/rest-api.md) lists every read parameter (app-user\\nwrites are described in [End users](end-users.md)); your instance's own OpenAPI document, for its current\\nschema, is at `/api/docs` (admins).\\n\\nThe examples below use the [example site](example-site.md)'s models.\\n\\n## Tokens\\n\\nCreate a **delivery role** (Network → Roles → New role, kind _Delivery_) with `read` on the models your site\\nneeds, then an API token bound to it (Settings → API tokens). Send it as a bearer token:\\n\\n```sh\\ncurl -H \\\"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\\\" \\\"$SHAPIO_URL/api/content/articles?locale=fr\\\"\\n```\\n\\n- Delivery tokens can only ever read, whatever their role says.\\n- A role's grant covers every field marked `public` (the default); `public: false` fields are hidden unless the\\n grant names them.\\n- Without a token, a request is _anonymous_: it gets what the built-in **public** app role grants, which is\\n nothing until you allow it (Network → Roles → App roles). Use that for content anyone may read from the\\n browser. App users' own tokens are covered in [End users](end-users.md).\\n\\n## Sites\\n\\nOne Shapio instance can host several [sites](sites.md) that share the content types but each have their own\\ncontent, tokens and snapshots. Every delivery request reads exactly one site:\\n\\n1. **The token's site.** Delivery tokens belong to the site they were created on, and only ever read it.\\n2. **The site the request names**, with `?site=<key>` or the `Shapio-Site: <key>` header. Anonymous callers and\\n network admin tokens use this to pick a site.\\n3. **The primary site**, when neither names one. An instance with a single site never needs to name it.\\n\\nNaming a different site than the token's is refused with `403 SITE_MISMATCH`, never redirected, and so is a\\nrequest whose header and `?site=` disagree. An unknown key is `404 SITE_NOT_FOUND`. Entries of another site\\nread as not found, and relations never cross sites.\\n\\n```sh\\ncurl \\\"$SHAPIO_URL/api/content/articles?site=marketing\\\"\\n```\\n\\nAnonymous reads get what the app roles bound to the request site's `public` audience grant. The primary site\\nbinds the built-in **public** role; a new site binds none, so it serves nothing anonymously until you bind one\\n([Sites](sites.md#app-users-and-anonymous-access)).\\n\\nWith `@shapio/client`, pass the site once:\\n\\n```ts\\nconst shapio = createClient({ baseUrl: process.env.SHAPIO_URL, token, site: 'marketing' });\\n```\\n\\nThe client sends it as `?site=` on delivery and snapshot reads, which keeps a cross-origin `GET` free of a\\nCORS preflight and keeps URL-keyed caches apart. Every other request (writes, GraphQL, the admin API) carries\\nthe `Shapio-Site` header. Leave `site` out to read the token's site, or the primary site.\\n\\n## Responses\\n\\n```json\\n{\\n \\\"data\\\": [\\n {\\n \\\"id\\\": \\\"6f2c…\\\",\\n \\\"locale\\\": \\\"fr\\\",\\n \\\"createdAt\\\": \\\"2026-10-01T09:12:44.512Z\\\",\\n \\\"updatedAt\\\": \\\"2026-10-01T09:30:02.104Z\\\",\\n \\\"publishedAt\\\": \\\"2026-10-01T09:30:02.104Z\\\",\\n \\\"title\\\": \\\"Modéliser du contenu sans déploiement\\\",\\n \\\"slug\\\": \\\"modelling-without-a-deploy\\\",\\n \\\"excerpt\\\": \\\"…\\\",\\n \\\"body\\\": {\\n \\\"format\\\": \\\"shapio-richtext\\\",\\n \\\"version\\\": 1,\\n \\\"doc\\\": { \\\"type\\\": \\\"doc\\\", \\\"content\\\": [] },\\n \\\"html\\\": \\\"<p>…</p>\\\"\\n },\\n \\\"cover\\\": { \\\"id\\\": \\\"…\\\", \\\"url\\\": \\\"…\\\", \\\"width\\\": 1600, \\\"height\\\": 900, \\\"alt\\\": \\\"…\\\", \\\"variants\\\": [] },\\n \\\"author\\\": \\\"0b7e…\\\",\\n \\\"publishedOn\\\": \\\"2026-09-01\\\"\\n }\\n ],\\n \\\"meta\\\": {\\n \\\"locale\\\": \\\"fr\\\",\\n \\\"snapshot\\\": 10,\\n \\\"pagination\\\": { \\\"page\\\": 1, \\\"pageSize\\\": 25, \\\"total\\\": 2, \\\"pageCount\\\": 1 }\\n }\\n}\\n```\\n\\n- Entries are flat: system attributes, then every readable field by API ID, `null` (or `[]`) when empty.\\n- **Rich text** is the stored JSON document plus `html`, rendered on the server from the JSON with an allow-list\\n sanitiser (safe link protocols only, images resolved through the media library).\\n- **Media** fields are asset objects with URLs and ready [variants](media.md#image-variants); private assets\\n carry an expiring signed URL.\\n- **Relations** are target IDs unless you `populate` them. A target that is not published, or that your token\\n may not read, is left out (never its ID).\\n- **Components** are objects; **dynamic zones** are arrays of objects with `__component` (the component's\\n API ID).\\n- A single type answers `/api/content/<API ID>` with `{ data: {…}, meta }`.\\n\\nErrors always look like `{ \\\"error\\\": { \\\"code\\\": \\\"…\\\", \\\"message\\\": \\\"…\\\", \\\"details\\\": … } }`: 400 for an invalid query,\\n401 without credentials for content that needs them, 403 when your role may not read the model, 404 for an\\nunknown model or entry.\\n\\n## Query parameters\\n\\n| Parameter | Example | Notes |\\n| ------------------ | ------------------------------------- | --------------------------------------------------------------------------------- |\\n| `locale` | `locale=fr` | falls back along the locale chain ([Localization](localization.md)) |\\n| `filters` | `filters[slug][$eq]=about` | see below |\\n| `sort` | `sort=publishedOn:desc,createdAt:asc` | fields marked sortable, `id`, `createdAt`, `updatedAt` |\\n| `page`, `pageSize` | `page=2&pageSize=50` | `pageSize` 25 by default, at most 100 |\\n| `fields` | `fields=title,slug` | top-level fields to return (system attributes always come) |\\n| `populate` | `populate=author` | relation paths: `author`, `author,tags.author`, or `*`; at most 3 levels |\\n| `q` | `q=snapshot` | searches the title field chosen in the model's display settings (400 without one) |\\n| `snapshot` | `snapshot=10` | read as of a publication snapshot (below) |\\n\\n### Filters\\n\\n`filters[<field>][<operator>]=<value>`, combined with `$and`, `$or` and `$not`:\\n\\n```sh\\ncurl -G \\\"$SHAPIO_URL/api/content/articles\\\" -H \\\"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\\\" \\\\\\n --data-urlencode 'filters[publishedOn][$gte]=2026-09-10' \\\\\\n --data-urlencode 'filters[$or][0][slug][$eq]=why-builds-pin-a-snapshot' \\\\\\n --data-urlencode 'filters[$or][1][slug][$eq]=modelling-without-a-deploy'\\n```\\n\\n| Operators | Field types |\\n| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\\n| `$eq`, `$ne`, `$in`, `$nin`, `$null`, `$notNull` | text, numbers, dates, enums, relations and media (booleans: `$eq`, `$ne`, `$null`, `$notNull`); on lists (`many` relations, multiple media/enums) `$eq` means \\\"contains\\\" |\\n| `$lt`, `$lte`, `$gt`, `$gte` | text, numbers, dates and times, on fields marked **filterable** or **sortable** |\\n| `$contains`, `$notContains`, `$containsi`, `$startsWith`, `$endsWith` | text fields marked **filterable** |\\n\\n`id`, `createdAt` and `updatedAt` can be filtered too (`publishedAt` is returned but cannot be filtered or\\nsorted). JSON, rich text, component and dynamic zone fields cannot be filtered. `$in` takes repeated values or `a,b`. Values are read\\nlike stored values, so `2026-10-01T10:00:00+02:00` matches `2026-10-01T08:00:00.000Z`. Unknown fields,\\noperators a type does not support, and filters or sorts on fields your token may not read are refused (400/403)\\nrather than ignored, so a filter can never reveal a hidden value.\\n\\n## Snapshots: one consistent moment\\n\\nEvery publish moves a global **publication snapshot** number forward; every delivery response reports the\\none it read in `meta.snapshot`. Pass `snapshot=N` and Shapio answers exactly as it would have at that moment,\\neven if more was published since:\\n\\n```sh\\ncurl -H \\\"Authorization: Bearer $SHAPIO_DELIVERY_TOKEN\\\" \\\"$SHAPIO_URL/api/content/pages?snapshot=10&locale=en\\\"\\n```\\n\\nA static site build should read the current snapshot once at the start and pass it with every request: then\\na publish in the middle of the build cannot produce a site that mixes two moments. The\\n[example site](example-site.md) does exactly this, and Shapio's deployment triggers carry the snapshot to build.\\n\\nOld snapshots are read through the current schema (a value stored under an earlier field type comes back as\\n`null`). A [change set](change-sets.md) goes live as one snapshot, schema and entries together, so a pinned\\nbuild sees all of it or none of it.\\n\\nTwo endpoints serve builds, with the same tokens as `/api/content` and only for models the token may read:\\n\\n| Endpoint | Answer |\\n| ------------------------------------------------ | ------------------------------------------------------------------------ |\\n| `GET /api/snapshots/current` | `{ snapshot, schemaVersion, publishedAt }`: what an unpinned read serves |\\n| `GET /api/snapshots/changes?from&to&after&limit` | entries and locales whose live content changed between the two snapshots |\\n\\nDetails, the change classification and incremental-build recipes are in\\n[Snapshots and the changes API](snapshots.md).\\n\\n## Caching\\n\\nResponses carry a strong `ETag` over the exact body and `Vary: Authorization, Cookie, Shapio-Site`. Send\\n`If-None-Match` to get `304 Not Modified` when nothing changed. Anonymous responses are `Cache-Control: public,\\nmax-age=0, must-revalidate`; authenticated ones `private`. A CDN that keys its cache on the URL alone and\\nignores `Vary` must be given the site as `?site=`, not as the header, so that two sites never share a cached\\nresponse.\\n\\n## Writes\\n\\nThe same routes accept `POST`, `PUT` and `DELETE` from app users whose roles allow it (for example, members\\nediting their own entries). Delivery tokens cannot write. See [End users](end-users.md). Editors and your\\nbuild tools use the admin API (`/api/admin/content/<key>`) with admin credentials.\\n\";\n","import { ResourceTemplate } from '@modelcontextprotocol/server';\nimport { serializeDefinition } from '@shapio/schema';\nimport type { ToolContext } from './context.js';\nimport { findDefinition, readSchema } from './definitions.js';\nimport { DELIVERY_API_DOC } from './generated/deliveryApiDoc.js';\n\nexport const SCHEMA_URI_TEMPLATE = 'shapio://schema/{apiKey}';\nexport const DELIVERY_DOC_URI = 'shapio://docs/delivery-api';\n\n/** Each definition in the pull format (`shapio schema pull`'s files), and the delivery API guide. */\nexport const registerResources = ({ server, client }: ToolContext) => {\n server.registerResource(\n 'schema',\n new ResourceTemplate(SCHEMA_URI_TEMPLATE, {\n list: async () => {\n const schema = await readSchema(client);\n return {\n resources: schema.definitions.map(({ definition }) => ({\n uri: `shapio://schema/${definition.apiKey}`,\n name: definition.apiKey,\n title: definition.label,\n mimeType: 'application/json',\n })),\n };\n },\n }),\n {\n title: 'Content type definition',\n description: 'A model or component in the schema file format, with stable IDs.',\n mimeType: 'application/json',\n },\n async (uri, variables) => {\n const apiKey = String(variables.apiKey);\n const { definition } = findDefinition(await readSchema(client), apiKey);\n return {\n contents: [{ uri: uri.href, mimeType: 'application/json', text: serializeDefinition(definition) }],\n };\n },\n );\n\n server.registerResource(\n 'delivery-api',\n DELIVERY_DOC_URI,\n {\n title: 'Delivery API guide',\n description: 'How sites and apps read published content: routes, filters, locales, snapshots, tokens.',\n mimeType: 'text/markdown',\n },\n (uri) => ({ contents: [{ uri: uri.href, mimeType: 'text/markdown', text: DELIVERY_API_DOC }] }),\n );\n};\n","import type { CallToolResult } from '@modelcontextprotocol/server';\nimport { ShapioApiError } from '@shapio/client';\n\n/** A tool's answer: the API response as pretty JSON text (what agents read best). */\nexport const jsonResult = (value: unknown): CallToolResult => ({\n content: [{ type: 'text', text: JSON.stringify(value ?? null, null, 2) }],\n});\n\n/**\n * A refusal or failure the agent should see and act on (a stale version, a missing permission, validation\n * issues), with Shapio's error code and details. Never thrown: the MCP client gets `isError`.\n */\nexport const errorResult = (error: unknown): CallToolResult => {\n const body =\n error instanceof ShapioApiError\n ? { status: error.status, code: error.code, message: error.message, details: error.details }\n : { code: 'TOOL_FAILED', message: error instanceof Error ? error.message : String(error) };\n return { isError: true, content: [{ type: 'text', text: JSON.stringify({ error: body }, null, 2) }] };\n};\n\n/** Runs a tool body, turning any failure into an error result. */\nexport const runTool = async (body: () => Promise<unknown>): Promise<CallToolResult> => {\n try {\n return jsonResult(await body());\n } catch (error) {\n return errorResult(error);\n }\n};\n","import { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { runTool } from './results.js';\n\nconst SET_ID = z.string().min(1).describe('Change set ID');\n\n/**\n * Change sets: the reviewable bundle of schema drafts and entry publications that ships as one snapshot.\n * Agents create and fill them; shipping is a person's call (`change_sets_ship` exists only with\n * --allow-ship, and the server also needs the token's role to hold changes.ship).\n */\nexport const registerChangeSetTools = ({ server, client, options }: ToolContext) => {\n server.registerTool(\n 'change_sets_list',\n {\n title: 'List change sets',\n description: 'Change sets, newest first (every status but discarded unless status is given).',\n inputSchema: z.object({\n status: z\n .string()\n .optional()\n .describe('Comma-separated: open, scheduled, shipping, shipped, failed, discarded'),\n cursor: z.string().optional(),\n limit: z.number().int().positive().max(100).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (query) => runTool(() => client.admin.changeSets.list(query)),\n );\n\n server.registerTool(\n 'change_sets_create',\n {\n title: 'Create a change set',\n description: 'An empty, open change set to collect schema drafts and entry publications for review.',\n inputSchema: z.object({\n title: z.string().min(1).max(200),\n description: z.string().max(5000).optional(),\n }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ title, description }) =>\n runTool(() => client.admin.changeSets.create({ title, ...(description ? { description } : {}) })),\n );\n\n server.registerTool(\n 'change_sets_add_entry',\n {\n title: 'Add an entry to a change set',\n description:\n \"Proposes publishing (or unpublishing) one entry locale when the set ships. The entry's current draft \" +\n 'is what ships; the review shows the field diff against what is live.',\n inputSchema: z.object({\n changeSetId: SET_ID,\n model: z.string().min(1).describe(\"The model's API ID\"),\n entryId: z.string().min(1),\n locale: z.string().optional().describe('Omit for non-localized models and the default locale'),\n action: z.enum(['publish', 'unpublish']).default('publish'),\n }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ changeSetId, model, entryId, locale, action }) =>\n runTool(() =>\n client.admin.changeSets.addEntry(changeSetId, {\n modelKey: model,\n entryId,\n action,\n ...(locale ? { locale } : {}),\n }),\n ),\n );\n\n server.registerTool(\n 'change_sets_review',\n {\n title: 'Review a change set',\n description:\n 'The set (status, version, items) and its review: field diffs per entry, the schema plan per draft ' +\n '(breaking, destructive, conversions), blocking issues, warnings and the consumers of affected fields.',\n inputSchema: z.object({ changeSetId: SET_ID }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ changeSetId }) =>\n runTool(async () => {\n const [set, review] = await Promise.all([\n client.admin.changeSets.get(changeSetId),\n client.admin.changeSets.review(changeSetId),\n ]);\n return { set, review };\n }),\n );\n\n if (options.allowShip) {\n server.registerTool(\n 'change_sets_ship',\n {\n title: 'Ship a change set',\n description:\n 'Makes the set live as one snapshot. Only when the person you work for asked for it. expectedVersion ' +\n 'is the set version change_sets_review showed; breaking or destructive schema changes need the ' +\n \"acknowledgement. Refused when the token's role lacks changes.ship.\",\n inputSchema: z.object({\n changeSetId: SET_ID,\n expectedVersion: z.number().int().nonnegative(),\n acknowledgeBreaking: z.boolean().optional(),\n acknowledgeDestructive: z.boolean().optional(),\n }),\n annotations: { destructiveHint: true, openWorldHint: false },\n },\n ({ changeSetId, ...body }) => runTool(() => client.admin.changeSets.ship(changeSetId, body)),\n );\n }\n};\n","import type { ContentFilter, ContentSort } from '@shapio/client';\nimport { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { findDefinition, readSchema, routeKeyOf } from '../definitions.js';\nimport { runTool } from './results.js';\n\nconst MODEL = z.string().min(1).describe('The model\\'s API ID (singular, e.g. \"article\")');\nconst LOCALE = z.string().min(1).optional().describe('Locale code; the default locale when omitted');\nconst PUBLISHED = z\n .boolean()\n .optional()\n .describe('Read published content through the delivery API instead of drafts (implied by snapshot)');\nconst SNAPSHOT = z\n .number()\n .int()\n .nonnegative()\n .optional()\n .describe('Read published content as of publication snapshot N');\n\nconst QUERY = z.object({\n model: MODEL,\n filters: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Filter tree by field API ID, e.g. { \"title\": { \"$containsi\": \"launch\" } }; $and/$or take lists',\n ),\n sort: z.array(z.object({ field: z.string().min(1), direction: z.enum(['asc', 'desc']) })).optional(),\n page: z.number().int().positive().optional(),\n pageSize: z.number().int().positive().max(100).optional(),\n q: z.string().optional().describe('Free-text search over the title field'),\n locale: LOCALE,\n fields: z.array(z.string()).optional().describe('Top-level fields to return'),\n populate: z.array(z.string()).optional().describe('Relation paths to expand, e.g. \"author\"'),\n status: z\n .enum(['draft', 'published', 'modified'])\n .optional()\n .describe('Drafts only: entries in this status'),\n published: PUBLISHED,\n snapshot: SNAPSHOT,\n});\n\nconst DATA = z\n .record(z.string(), z.unknown())\n .describe(\"Field values by API ID. Rich text is Shapio's JSON document format, never HTML.\");\n\n/** Entries: query and read (drafts or published), create and update drafts. Never publishes. */\nexport const registerContentTools = ({ server, client }: ToolContext) => {\n server.registerTool(\n 'content_query',\n {\n title: 'Query entries',\n description:\n \"A page of a model's entries. Drafts by default (what editors see); published=true or snapshot=N reads \" +\n 'what the delivery API serves.',\n inputSchema: QUERY,\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ model, published, snapshot, status, filters, sort, ...rest }) =>\n runTool(async () => {\n const query = {\n ...rest,\n ...(filters ? { filters: filters as ContentFilter } : {}),\n ...(sort ? { sort: sort as ContentSort[] } : {}),\n };\n if (published || snapshot !== undefined) {\n const { definition } = findDefinition(await readSchema(client), model);\n const routeKey = routeKeyOf(definition);\n return definition.kind === 'singleton'\n ? client.delivery.singleton(routeKey, {\n ...(rest.locale ? { locale: rest.locale } : {}),\n ...(snapshot !== undefined ? { snapshot } : {}),\n })\n : client.delivery.list(routeKey, { ...query, ...(snapshot !== undefined ? { snapshot } : {}) });\n }\n return client.admin.content.list(model, { ...query, ...(status ? { status } : {}) });\n }),\n );\n\n server.registerTool(\n 'content_get',\n {\n title: 'Read an entry',\n description:\n \"One entry: its draft with every locale's status and version (send version back as expectedVersion \" +\n 'to content_update), or the published version when published=true or snapshot=N.',\n inputSchema: z.object({\n model: MODEL,\n id: z.string().min(1),\n locale: LOCALE,\n published: PUBLISHED,\n snapshot: SNAPSHOT,\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ model, id, locale, published, snapshot }) =>\n runTool(async () => {\n if (published || snapshot !== undefined) {\n const { definition } = findDefinition(await readSchema(client), model);\n return client.delivery.get(routeKeyOf(definition), id, {\n ...(locale ? { locale } : {}),\n ...(snapshot !== undefined ? { snapshot } : {}),\n });\n }\n return client.admin.content.get(model, id, locale ? { locale } : {});\n }),\n );\n\n server.registerTool(\n 'content_create',\n {\n title: 'Create a draft entry',\n description:\n 'Creates an entry as a draft (never published). Validated by the server against the live model. ' +\n 'Add it to a change set with change_sets_add_entry to propose publishing it.',\n inputSchema: z.object({ model: MODEL, data: DATA, locale: LOCALE }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ model, data, locale }) =>\n runTool(() => client.admin.content.create(model, { data, ...(locale ? { locale } : {}) })),\n );\n\n server.registerTool(\n 'content_update',\n {\n title: 'Update a draft entry',\n description:\n \"Saves changed fields into one locale's draft (absent fields are kept, null clears). expectedVersion is \" +\n 'the version content_get returned; a stale one is refused (CONTENT_VERSION_CONFLICT): read again and redo. ' +\n 'Pass expectedVersion null to start a new locale of the entry.',\n inputSchema: z.object({\n model: MODEL,\n id: z.string().min(1),\n data: DATA,\n expectedVersion: z.number().int().nonnegative().nullable(),\n locale: LOCALE,\n }),\n annotations: { destructiveHint: false, idempotentHint: false, openWorldHint: false },\n },\n ({ model, id, data, expectedVersion, locale }) =>\n runTool(() =>\n client.admin.content.update(model, id, { data, expectedVersion, ...(locale ? { locale } : {}) }),\n ),\n );\n};\n","import { HEALTH_RULES } from '@shapio/client';\nimport { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { findDefinition, readSchema } from '../definitions.js';\nimport { runTool } from './results.js';\n\n/** Checks and signals: pre-flight for one entry, content health findings, field usage by consumers. */\nexport const registerInsightTools = ({ server, client }: ToolContext) => {\n server.registerTool(\n 'preflight_run',\n {\n title: 'Pre-flight an entry',\n description:\n 'What publishing these locales of an entry would run into (validation, missing locales, references, ' +\n 'alt text), without publishing anything.',\n inputSchema: z.object({\n model: z.string().min(1).describe(\"The model's API ID\"),\n id: z.string().min(1),\n locales: z.array(z.string()).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ model, id, locales }) =>\n runTool(() => client.admin.preflight.run(model, id, locales ? { locales } : {})),\n );\n\n server.registerTool(\n 'health_list',\n {\n title: 'List content health findings',\n description: `Open findings of the content health rules (${HEALTH_RULES.join(', ')}), by rule and model.`,\n inputSchema: z.object({\n rule: z.enum(HEALTH_RULES).optional(),\n model: z.string().optional().describe(\"The model's API ID\"),\n cursor: z.string().optional(),\n limit: z.number().int().positive().max(100).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ model, ...query }) =>\n runTool(() => client.admin.contentHealth.list({ ...query, ...(model ? { modelKey: model } : {}) })),\n );\n\n server.registerTool(\n 'usage_fields',\n {\n title: 'Field usage',\n description:\n 'Which fields of a model sites and apps read, per API token, over the last N days: check before ' +\n 'renaming or removing a field.',\n inputSchema: z.object({\n model: z.string().min(1).describe(\"The model's API ID\"),\n days: z.number().int().positive().max(365).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n ({ model, days }) =>\n runTool(async () => {\n const { definition } = findDefinition(await readSchema(client), model);\n return client.admin.usage.fields({ modelId: definition.id, ...(days ? { days } : {}) });\n }),\n );\n};\n","import { realpath } from 'node:fs/promises';\nimport { isAbsolute, relative, resolve } from 'node:path';\nimport { uploadFile } from '@shapio/client/node';\nimport { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { runTool } from './results.js';\n\n/**\n * The file a `media_upload` may read: inside the media root after resolving symlinks, so an agent (or text\n * injected into what it reads) cannot have the server read ~/.ssh or anything else outside the project.\n */\nexport const resolveMediaPath = async (mediaRoot: string, path: string): Promise<string> => {\n const root = await realpath(mediaRoot);\n const target = await realpath(resolve(root, path)).catch(() => {\n throw new Error(`No file at ${path} (relative to the media root ${root})`);\n });\n const inside = relative(root, target);\n if (inside === '' || inside.startsWith('..') || isAbsolute(inside)) {\n throw new Error(\n `media_upload only reads files under the media root (${root}); start the server with --media-root to change it`,\n );\n }\n return target;\n};\n\n/** The media library: browse, and upload files from the media root. */\nexport const registerMediaTools = ({ server, client, options }: ToolContext) => {\n server.registerTool(\n 'media_list',\n {\n title: 'List media',\n description: 'A page of media assets (ID, filename, type, alt text, visibility, URLs), newest first.',\n inputSchema: z.object({\n folder: z.string().optional().describe('A folder ID, or \"root\" for assets in no folder'),\n mimeType: z.string().optional().describe('\"image/png\" or \"image/*\"'),\n search: z.string().optional(),\n cursor: z.string().optional().describe('nextCursor of the previous page'),\n limit: z.number().int().positive().max(100).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (query) => runTool(() => client.admin.media.assets.list(query)),\n );\n\n server.registerTool(\n 'media_upload',\n {\n title: 'Upload a file',\n description:\n `Uploads a local file into the media library and returns the asset (use its ID in media fields). Only ` +\n `files under ${options.mediaRoot} can be read. Media is stored at once (it is not part of change sets).`,\n inputSchema: z.object({\n path: z.string().min(1).describe('Path relative to the media root (or absolute, inside it)'),\n alt: z.string().max(1000).optional().describe('Alt text for images'),\n mimeType: z.string().optional().describe('Needed when the extension is not a common one'),\n folderId: z.string().optional(),\n visibility: z.enum(['public', 'private']).optional(),\n }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ path, alt, mimeType, folderId, visibility }) =>\n runTool(async () => {\n const file = await resolveMediaPath(options.mediaRoot, path);\n const asset = await uploadFile(client, {\n baseUrl: options.baseUrl,\n path: file,\n ...(mimeType ? { mimeType } : {}),\n ...(folderId ? { folderId } : {}),\n ...(visibility ? { visibility } : {}),\n });\n return alt\n ? client.admin.media.assets.update(asset.id, { expectedVersion: asset.version, alt })\n : asset;\n }),\n );\n};\n","import { randomUUID } from 'node:crypto';\nimport type { ChangeSet, ChangeSetSchemaItem, ShapioClient } from '@shapio/client';\nimport { isStableId, type DefinitionInput } from '@shapio/schema';\nimport { readSchema } from './definitions.js';\n\n/** A definition as an agent writes it: the authored format, IDs optional, references by API ID allowed. */\nexport type DraftDefinition = Record<string, unknown> & { apiKey?: unknown; kind?: unknown; id?: unknown };\n\ntype FieldLike = { type?: unknown; settings?: Record<string, unknown> };\n\nconst schemaItemsOf = (set: ChangeSet) =>\n set.items.filter((item): item is ChangeSetSchemaItem => item.kind === 'schema');\n\n/**\n * Relation targets and component references are stable IDs. Agents think in API IDs, so a reference that\n * is not an ID is looked up among the active definitions and the set's drafts (and this definition itself,\n * for a self-relation); anything unknown is left for the server to report.\n */\nconst resolveReferences = (definition: DraftDefinition, idsByApiKey: ReadonlyMap<string, string>) => {\n const resolve = (value: unknown) =>\n typeof value === 'string' && !isStableId(value) ? (idsByApiKey.get(value) ?? value) : value;\n const fields = Array.isArray(definition.fields) ? (definition.fields as FieldLike[]) : [];\n return {\n ...definition,\n fields: fields.map((field) => {\n const settings = field.settings;\n if (!settings) {\n return field;\n }\n if (field.type === 'relation') {\n return { ...field, settings: { ...settings, target: resolve(settings.target) } };\n }\n if (field.type === 'component') {\n return { ...field, settings: { ...settings, component: resolve(settings.component) } };\n }\n if (field.type === 'dynamiczone' && Array.isArray(settings.components)) {\n return { ...field, settings: { ...settings, components: settings.components.map(resolve) } };\n }\n return field;\n }),\n };\n};\n\n/**\n * Puts a definition into a change set as a draft: picks its stable ID (the active definition's, the set's\n * existing draft's, or a new one), its base version and the draft version to replace, then lets the server\n * parse, validate and plan it. Nothing goes live until a person ships the set.\n */\nexport const putDefinitionDraft = async (\n client: ShapioClient,\n changeSetId: string,\n definition: DraftDefinition,\n) => {\n if (typeof definition.apiKey !== 'string' || typeof definition.kind !== 'string') {\n throw new Error('A definition needs at least \"kind\" (collection, singleton or component) and \"apiKey\"');\n }\n const [schema, set] = await Promise.all([readSchema(client), client.admin.changeSets.get(changeSetId)]);\n const drafts = schemaItemsOf(set);\n const apiKey = definition.apiKey;\n const explicitId = typeof definition.id === 'string' ? definition.id : undefined;\n const active = schema.definitions.find(\n ({ definition: candidate }) =>\n candidate.id === explicitId || (!explicitId && candidate.apiKey === apiKey),\n );\n const drafted = drafts.find(\n (item) => item.definitionId === explicitId || (!explicitId && item.apiKey === apiKey),\n );\n const id = explicitId ?? active?.definition.id ?? drafted?.definitionId ?? randomUUID();\n const idsByApiKey = new Map<string, string>([\n ...schema.definitions.map(({ definition: candidate }) => [candidate.apiKey, candidate.id] as const),\n ...drafts.map((item) => [item.apiKey, item.definitionId] as const),\n [apiKey, id],\n ]);\n const payload = resolveReferences({ ...definition, id }, idsByApiKey) as unknown as DefinitionInput;\n const draft = await client.admin.changeSets.putSchemaDraft(changeSetId, id, {\n category: definition.kind === 'component' ? 'component' : 'model',\n definition: payload,\n baseVersion: active?.version ?? null,\n ...(drafted ? { expectedDraftVersion: drafted.draftVersion } : {}),\n });\n return { changeSetId, definitionId: id, operation: draft.operation, draftVersion: draft.version, draft };\n};\n","import { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { findDefinition, readSchema, summarize } from '../definitions.js';\nimport { putDefinitionDraft } from '../schemaDrafts.js';\nimport { runTool } from './results.js';\n\nconst READ_ONLY = { readOnlyHint: true, openWorldHint: false } as const;\n\nconst DEFINITION_DESCRIPTION =\n 'A whole definition in Shapio\\'s authored format: { kind: \"collection\" | \"singleton\" | \"component\", apiKey, ' +\n 'label, pluralApiKey? (collections), localized?, draftAndPublish?, fields: [{ apiKey, label, type, required?, ' +\n 'localized?, settings? }] }. IDs are optional: an existing definition keeps its IDs (matched by API ID). ' +\n 'Relation targets and component references may be given as API IDs. Read shapio://schema/{apiKey} to see ' +\n 'the format of an existing one.';\n\n/** The schema: list and read definitions, and draft changes into a change set (never activated here). */\nexport const registerSchemaTools = ({ server, client }: ToolContext) => {\n server.registerTool(\n 'schema_list',\n {\n title: 'List content types',\n description:\n 'Every model (collection, singleton) and component with its API IDs, version and fields (types only). ' +\n 'Delivery reads use pluralApiKey for collections.',\n inputSchema: z.object({}),\n annotations: READ_ONLY,\n },\n () =>\n runTool(async () => {\n const schema = await readSchema(client);\n return { schemaVersion: schema.schemaVersion, definitions: schema.definitions.map(summarize) };\n }),\n );\n\n server.registerTool(\n 'schema_get',\n {\n title: 'Read a content type',\n description: 'One definition in full (fields with settings), by API ID or stable ID, with its version.',\n inputSchema: z.object({\n apiKey: z.string().min(1).describe('API ID (or stable ID) of the definition'),\n }),\n annotations: READ_ONLY,\n },\n ({ apiKey }) => runTool(async () => findDefinition(await readSchema(client), apiKey)),\n );\n\n server.registerTool(\n 'schema_draft',\n {\n title: 'Draft a content type change',\n description:\n 'Proposes a new or changed definition as a draft in a change set (a new set when changeSetId is ' +\n 'omitted). Nothing changes on the live schema until a person reviews and ships the set. Returns the ' +\n 'change set ID; read change_sets_review next.',\n inputSchema: z.object({\n definition: z.record(z.string(), z.unknown()).describe(DEFINITION_DESCRIPTION),\n changeSetId: z.string().optional().describe('An open change set; omit to start a new one'),\n title: z.string().min(1).max(200).optional().describe('Title of the new change set'),\n }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ definition, changeSetId, title }) =>\n runTool(async () => {\n const apiKey = typeof definition.apiKey === 'string' ? definition.apiKey : 'draft';\n const setId =\n changeSetId ?? (await client.admin.changeSets.create({ title: title ?? `Schema: ${apiKey}` })).id;\n return putDefinitionDraft(client, setId, definition);\n }),\n );\n\n server.registerTool(\n 'change_sets_add_schema_draft',\n {\n title: 'Add a schema draft to a change set',\n description:\n \"Puts a new or changed definition into an existing change set as a draft (replaces this set's \" +\n 'earlier draft of the same definition). Ships only when a person ships the set.',\n inputSchema: z.object({\n changeSetId: z.string().min(1),\n definition: z.record(z.string(), z.unknown()).describe(DEFINITION_DESCRIPTION),\n }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ changeSetId, definition }) => runTool(() => putDefinitionDraft(client, changeSetId, definition)),\n );\n};\n","import { z } from 'zod';\nimport type { ToolContext } from '../context.js';\nimport { runTool } from './results.js';\n\n/** Publication snapshots: the ledger, the diff between two, and restore (as a reviewable change set). */\nexport const registerSnapshotTools = ({ server, client }: ToolContext) => {\n server.registerTool(\n 'snapshots_list',\n {\n title: 'List snapshots',\n description: 'The publication ledger, newest first: what went live, when, why and by whom.',\n inputSchema: z.object({\n cursor: z.string().optional(),\n limit: z.number().int().positive().max(100).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (query) => runTool(() => client.admin.snapshots.list(query)),\n );\n\n server.registerTool(\n 'snapshots_changes',\n {\n title: 'Changes between snapshots',\n description:\n 'Which entries were published, updated or unpublished between snapshot \"from\" and \"to\" (default: now). ' +\n 'Names entries, never values.',\n inputSchema: z.object({\n from: z.number().int().nonnegative(),\n to: z.number().int().nonnegative().optional(),\n after: z.string().optional().describe('nextCursor of the previous page'),\n limit: z.number().int().positive().max(500).optional(),\n }),\n annotations: { readOnlyHint: true, openWorldHint: false },\n },\n (query) => runTool(() => client.snapshots.changes(query)),\n );\n\n server.registerTool(\n 'snapshots_restore',\n {\n title: 'Propose restoring a snapshot',\n description:\n 'Creates an open change set that would bring live content back to what snapshot N served. Nothing ' +\n 'changes until a person ships it; the schema is never rolled back.',\n inputSchema: z.object({ seq: z.number().int().positive() }),\n annotations: { destructiveHint: false, openWorldHint: false },\n },\n ({ seq }) => runTool(() => client.admin.snapshots.restore(seq)),\n );\n};\n","import { McpServer } from '@modelcontextprotocol/server';\nimport { createClient, type ShapioClient } from '@shapio/client';\nimport packageJson from '../package.json' with { type: 'json' };\nimport type { ToolContext } from './context.js';\nimport type { McpOptions } from './options.js';\nimport { registerPrompts } from './prompts.js';\nimport { registerResources } from './resources.js';\nimport { registerChangeSetTools } from './tools/changeSets.js';\nimport { registerContentTools } from './tools/content.js';\nimport { registerInsightTools } from './tools/insights.js';\nimport { registerMediaTools } from './tools/media.js';\nimport { registerSchemaTools } from './tools/schema.js';\nimport { registerSnapshotTools } from './tools/snapshots.js';\n\nexport const MCP_SERVER_NAME = 'shapio';\nexport const MCP_SERVER_VERSION: string = packageJson.version;\n\nconst INSTRUCTIONS =\n 'Shapio is a headless CMS whose content types are live data. Agents propose, people ship: draft schema ' +\n 'changes and entries, collect them in a change set, and leave shipping to a person. Model and field ' +\n 'identifiers are called \"API IDs\". Read shapio://docs/delivery-api for how sites read content.';\n\n/** The MCP server for one Shapio instance, with every tool, resource and prompt registered. */\nexport const createShapioMcpServer = (\n options: McpOptions,\n client: ShapioClient = createClient({\n baseUrl: options.baseUrl,\n token: options.token,\n ...(options.site !== undefined ? { site: options.site } : {}),\n }),\n): McpServer => {\n const server = new McpServer(\n { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION },\n { instructions: INSTRUCTIONS },\n );\n const context: ToolContext = { server, client, options };\n registerSchemaTools(context);\n registerContentTools(context);\n registerMediaTools(context);\n registerInsightTools(context);\n registerChangeSetTools(context);\n registerSnapshotTools(context);\n registerResources(context);\n registerPrompts(context);\n return server;\n};\n","import { resolve } from 'node:path';\nimport { parseArgs } from 'node:util';\n\n/** How the server was started: the Shapio instance, its token, and the two guards. */\nexport type McpOptions = {\n /** Shapio's base URL including any BASE_PATH (`SHAPIO_URL`). */\n baseUrl: string;\n /** An admin-scope API token (`SHAPIO_TOKEN`). Give its role no `changes.ship`: shipping stays with people. */\n token: string;\n /** Registers `change_sets_ship` (`--allow-ship`). A client-side guard only: the token's role decides. */\n allowShip: boolean;\n /** `media_upload` reads files only under this directory (`--media-root`, default: the working directory). */\n mediaRoot: string;\n /**\n * The site key every request is about (`--site`, else `SHAPIO_SITE`), on multi-site instances. Left out:\n * the token's site (a site token), else the primary site. A site token cannot name another site.\n */\n site?: string;\n};\n\n/** A site key as Shapio creates them (sites are named by key in URLs, `?site=` and config). */\nconst SITE_KEY = /^[a-z][a-z0-9-]{0,62}$/;\n\nexport const USAGE = `Usage: shapio-mcp [--allow-ship] [--media-root <dir>] [--site <key>]\n\nA Model Context Protocol server (stdio) for a Shapio instance.\n\nEnvironment:\n SHAPIO_URL Shapio's base URL, including any BASE_PATH (e.g. https://cms.example.com)\n SHAPIO_TOKEN An admin-scope API token. Give its role no \"changes.ship\" permission: agents propose\n change sets, people ship them.\n SHAPIO_SITE The site key to work on (multi-site instances); --site overrides it. Default: the\n token's site, else the primary site.\n\nOptions:\n --allow-ship Offer the change_sets_ship tool (the token's role must also allow changes.ship)\n --media-root <dir> Directory media_upload may read files from (default: the working directory)\n --site <key> The site to work on (overrides SHAPIO_SITE)\n -h, --help Show this help\n`;\n\nexport class OptionsError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OptionsError';\n }\n}\n\n/** Reads the command line and environment; throws OptionsError with a message meant for stderr. */\nexport const parseOptions = (\n argv: readonly string[],\n env: Readonly<Record<string, string | undefined>>,\n cwd: string,\n): McpOptions | 'help' => {\n let parsed;\n try {\n parsed = parseArgs({\n args: [...argv],\n options: {\n 'allow-ship': { type: 'boolean', default: false },\n 'media-root': { type: 'string' },\n site: { type: 'string' },\n help: { type: 'boolean', short: 'h', default: false },\n },\n strict: true,\n allowPositionals: false,\n });\n } catch (error) {\n throw new OptionsError(error instanceof Error ? error.message : String(error));\n }\n if (parsed.values.help) {\n return 'help';\n }\n const baseUrl = env.SHAPIO_URL?.trim();\n const token = env.SHAPIO_TOKEN?.trim();\n if (!baseUrl || !/^https?:\\/\\//.test(baseUrl)) {\n throw new OptionsError('Set SHAPIO_URL to the Shapio base URL (http:// or https://).');\n }\n if (!token) {\n throw new OptionsError('Set SHAPIO_TOKEN to an admin-scope API token.');\n }\n const site = (parsed.values.site ?? env.SHAPIO_SITE)?.trim() || undefined;\n if (site !== undefined && !SITE_KEY.test(site)) {\n throw new OptionsError(`\"${site}\" is not a site key (lower case, starting with a letter).`);\n }\n return {\n baseUrl: baseUrl.replace(/\\/+$/, ''),\n token,\n allowShip: parsed.values['allow-ship'],\n mediaRoot: resolve(cwd, parsed.values['media-root'] ?? '.'),\n ...(site !== undefined ? { site } : {}),\n };\n};\n"],"mappings":";;;;;;;;;;;;;ACGA,MAAM,eAAe,UAAkB,EACrC,UAAU,CAAC;CAAE,MAAM;CAAiB,SAAS;EAAE,MAAM;EAAiB;CAAK;AAAE,CAAC,EAChF;;AAGA,MAAa,mBAAmB,EAAE,aAA0B;CAC1D,OAAO,eACL,sBACA;EACE,OAAO;EACP,aAAa;EACb,YAAY,EAAE,OAAO,EACnB,SAAS,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,+CAA6C,EACnF,CAAC;CACH,IACC,EAAE,cACD,YACE,qCAAqC,QAAQ;;;4JAQ/C,CACJ;CAEA,OAAO,eACL,qBACA;EACE,OAAO;EACP,aAA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
|
+
"description": "MCP server for Shapio: lets coding agents model content, write drafts and open change sets for review.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://shapio.dev",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/mybrokengnome/shapio.git",
|
|
10
|
+
"directory": "packages/mcp"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/mybrokengnome/shapio/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=24"
|
|
18
|
+
},
|
|
19
|
+
"bin": {
|
|
20
|
+
"shapio-mcp": "./dist/bin.js"
|
|
21
|
+
},
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"@shapio/source": "./src/index.ts",
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"dist"
|
|
31
|
+
],
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"@modelcontextprotocol/server": "2.2.0",
|
|
34
|
+
"@shapio/client": "0.2.0",
|
|
35
|
+
"@shapio/schema": "0.2.0",
|
|
36
|
+
"zod": "4.6.5"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@modelcontextprotocol/client": "2.2.0",
|
|
40
|
+
"@types/node": "24.19.1",
|
|
41
|
+
"tsdown": "0.23.0",
|
|
42
|
+
"typescript": "6.0.3",
|
|
43
|
+
"vitest": "5.0.3"
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"build": "node scripts/embedDocs.mjs && tsdown",
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
51
|
+
}
|
|
52
|
+
}
|