@formancy/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 +202 -0
- package/NOTICE +4 -0
- package/dist/index.d.mts +119 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +2 -0
- package/dist/main.d.mts +1 -0
- package/dist/main.mjs +27 -0
- package/dist/main.mjs.map +1 -0
- package/dist/server-CdcuxHHN.mjs +280 -0
- package/dist/server-CdcuxHHN.mjs.map +1 -0
- package/package.json +54 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
//#region src/tools.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* What formancy can be asked to do by a coding agent, as plain functions.
|
|
5
|
+
*
|
|
6
|
+
* Separated from the MCP server itself for the same reason `server-core` is separated
|
|
7
|
+
* from `server`: a use-case that can only be exercised through a transport is one nobody
|
|
8
|
+
* can test. Everything here is a function from JSON to JSON.
|
|
9
|
+
*
|
|
10
|
+
* **The tools check first and act second.** `publish_form` validates locally before it
|
|
11
|
+
* opens a socket, so an invalid document never reaches the server and the model gets the
|
|
12
|
+
* reason rather than a 422. That is possible because the format has a published JSON
|
|
13
|
+
* Schema and the expressions are statically type-checked — a generated document is
|
|
14
|
+
* checkable before anything is done with it.
|
|
15
|
+
*/
|
|
16
|
+
/** A tool's answer: what happened, and what the agent should do about it. */
|
|
17
|
+
interface ToolResult {
|
|
18
|
+
/** False means the agent must fix something before trying again. */
|
|
19
|
+
readonly ok: boolean;
|
|
20
|
+
/** Prose for the model. Written to be acted on, not logged. */
|
|
21
|
+
readonly summary: string;
|
|
22
|
+
/** The machine-readable part, when there is one. */
|
|
23
|
+
readonly data?: unknown;
|
|
24
|
+
}
|
|
25
|
+
/** Where a formancy server is, and how to prove who you are to it. */
|
|
26
|
+
interface ServerAccess {
|
|
27
|
+
readonly baseUrl: string;
|
|
28
|
+
readonly apiKey: string;
|
|
29
|
+
/** Injected so tests do not need a socket. */
|
|
30
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Everything the spec allows, so a model does not have to guess.
|
|
34
|
+
*
|
|
35
|
+
* The cheapest tool here and probably the most valuable: without it a model
|
|
36
|
+
* invents `type: "phone"` or `type: "email"` from its memory of other form
|
|
37
|
+
* builders, gets a validation error, and burns a turn finding out that `text`
|
|
38
|
+
* with `format: "email"` is the answer. Told up front, it does not.
|
|
39
|
+
*/
|
|
40
|
+
export declare function describeSpec(): ToolResult;
|
|
41
|
+
/**
|
|
42
|
+
* Check a document without publishing it — the server's publish checks, in the
|
|
43
|
+
* gate's order. Only the analysis of regular-expression `pattern`s stays on
|
|
44
|
+
* the server: it needs an analysis engine this package does not carry, and the
|
|
45
|
+
* server's refusal names the pattern.
|
|
46
|
+
*
|
|
47
|
+
* Schema validity, the engine's compile and expression sanity are different
|
|
48
|
+
* failures with different fixes, and a later check means nothing in a document
|
|
49
|
+
* an earlier one has rejected. So the structure is checked first, then whether
|
|
50
|
+
* the engine would open the document at all, then whether its expressions
|
|
51
|
+
* would ever do anything.
|
|
52
|
+
*
|
|
53
|
+
* The middle check was once missing, and this tool told a model that a form
|
|
54
|
+
* with a misspelled field name was valid: the validator does not read CEL and
|
|
55
|
+
* the expression check skips what the engine refuses, so nothing here asked
|
|
56
|
+
* the engine. The server did, and refused it.
|
|
57
|
+
*/
|
|
58
|
+
export declare function validateForm(document: unknown): ToolResult;
|
|
59
|
+
/**
|
|
60
|
+
* What a change does to the submissions already collected.
|
|
61
|
+
*
|
|
62
|
+
* The question an agent cannot answer by reading the two documents, and the
|
|
63
|
+
* one whose wrong answer is permanent. `breaking` is not advice.
|
|
64
|
+
*/
|
|
65
|
+
export declare function diffForms(before: unknown, after: unknown): ToolResult;
|
|
66
|
+
/**
|
|
67
|
+
* Publish, but check first.
|
|
68
|
+
*
|
|
69
|
+
* The local validation is not an optimisation. A model that gets a 422 back
|
|
70
|
+
* has to guess what the server meant from an error shape it has never seen;
|
|
71
|
+
* a model that gets `expressionProblems` back is told which rule, in which
|
|
72
|
+
* words, and what to write instead. And an invalid document never travels.
|
|
73
|
+
*/
|
|
74
|
+
export declare function publishForm(access: ServerAccess, path: string, document: unknown): Promise<ToolResult>;
|
|
75
|
+
export declare function listForms(access: ServerAccess): Promise<ToolResult>;
|
|
76
|
+
export declare function getForm(access: ServerAccess, path: string): Promise<ToolResult>;
|
|
77
|
+
export declare function listSubmissions(access: ServerAccess, path: string): Promise<ToolResult>;
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/server.d.ts
|
|
80
|
+
/**
|
|
81
|
+
* The tools, wired to the protocol.
|
|
82
|
+
*
|
|
83
|
+
* Thin on purpose: every one of these is a call into `tools.ts` and a
|
|
84
|
+
* conversion of the answer into MCP's content shape. The logic is tested
|
|
85
|
+
* without a protocol, because a use-case that can only be exercised through a
|
|
86
|
+
* transport is a use-case nobody tests properly.
|
|
87
|
+
*/
|
|
88
|
+
interface McpServerOptions {
|
|
89
|
+
/**
|
|
90
|
+
* Where a formancy server is, if there is one.
|
|
91
|
+
*
|
|
92
|
+
* Absent is a supported state and not a degraded one: the four local tools
|
|
93
|
+
* — describe_spec, validate_form, diff_forms and the checking half of
|
|
94
|
+
* publishing — need no server at all, which means an agent can author and
|
|
95
|
+
* verify a whole form before anybody has deployed anything.
|
|
96
|
+
*/
|
|
97
|
+
readonly access?: ServerAccess;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Names and descriptions, apart from the wiring.
|
|
101
|
+
*
|
|
102
|
+
* Exported because the description is the prompt: it is the only thing telling
|
|
103
|
+
* a model when to reach for a tool, and a wrong one means a tool that is never
|
|
104
|
+
* called or called for the wrong reason. Kept where it can be read and tested
|
|
105
|
+
* rather than buried in a registration call.
|
|
106
|
+
*/
|
|
107
|
+
export declare const TOOL_DEFINITIONS: {
|
|
108
|
+
readonly describe_spec: string;
|
|
109
|
+
readonly validate_form: string;
|
|
110
|
+
readonly diff_forms: string;
|
|
111
|
+
readonly publish_form: string;
|
|
112
|
+
readonly list_forms: "List the forms on the formancy server, with their current version.";
|
|
113
|
+
readonly get_form: "Fetch one form document from the formancy server, with its version and schema hash.";
|
|
114
|
+
readonly list_submissions: "List submissions for one form.";
|
|
115
|
+
};
|
|
116
|
+
export declare function createFormancyMcpServer(options?: McpServerOptions): McpServer;
|
|
117
|
+
//#endregion
|
|
118
|
+
export type { McpServerOptions, ServerAccess, ToolResult };
|
|
119
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/tools.ts","../src/server.ts"],"mappings":";;;;;;;;;;;;;;;;UAoBiB;;WAEN;;WAEA;;WAEA;;;UAIM;WACN;WACA;;WAEA,eAAe,WAAW;;;;;;;;;;wBAarB,gBAAgB;;;;;;;;;;;;;;;;;;wBA6BhB,aAAa,oBAAoB;;;;;;;wBA+CjC,UAAU,iBAAiB,iBAAiB;;;;;;;;;wBAiDtC,YACpB,QAAQ,cACR,cACA,oBACC,QAAQ;wBAgBW,UAAU,QAAQ,eAAe,QAAQ;wBAIzC,QAAQ,QAAQ,cAAc,eAAe,QAAQ;wBAIrD,gBAAgB,QAAQ,cAAc,eAAe,QAAQ;;;;;;;;;;;UClLlE;;;;;;;;;WASN,SAAS;;;;;;;;;;qBAWP;;;;;;;;;wBA4DG,wBAAwB,UAAS,mBAAwB"}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as getForm, c as publishForm, i as diffForms, l as validateForm, n as createFormancyMcpServer, o as listForms, r as describeSpec, s as listSubmissions, t as TOOL_DEFINITIONS } from "./server-CdcuxHHN.mjs";
|
|
2
|
+
export { TOOL_DEFINITIONS, createFormancyMcpServer, describeSpec, diffForms, getForm, listForms, listSubmissions, publishForm, validateForm };
|
package/dist/main.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/main.mjs
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { n as createFormancyMcpServer } from "./server-CdcuxHHN.mjs";
|
|
3
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
4
|
+
//#region src/main.ts
|
|
5
|
+
/**
|
|
6
|
+
* The executable. Reads the environment, wires the server, listens on stdio.
|
|
7
|
+
*
|
|
8
|
+
* A server is optional and its absence is a supported state: describe_spec,
|
|
9
|
+
* validate_form and diff_forms need nothing but this process, so an agent can
|
|
10
|
+
* author and check a whole form before anybody has deployed a backend. That is
|
|
11
|
+
* deliberately the useful half.
|
|
12
|
+
*
|
|
13
|
+
* stdio rather than HTTP, because the client launches this process and talks
|
|
14
|
+
* down its pipes. Nothing here listens on a port, so nothing here needs a
|
|
15
|
+
* port's worth of thinking about who can reach it.
|
|
16
|
+
*/
|
|
17
|
+
const baseUrl = process.env["FORMANCY_URL"];
|
|
18
|
+
const apiKey = process.env["FORMANCY_API_KEY"];
|
|
19
|
+
if (baseUrl === void 0 !== (apiKey === void 0)) throw new Error("Set FORMANCY_URL and FORMANCY_API_KEY together, or neither. With neither, the local tools still work.");
|
|
20
|
+
await createFormancyMcpServer(baseUrl === void 0 || apiKey === void 0 ? {} : { access: {
|
|
21
|
+
baseUrl,
|
|
22
|
+
apiKey
|
|
23
|
+
} }).connect(new StdioServerTransport());
|
|
24
|
+
//#endregion
|
|
25
|
+
export {};
|
|
26
|
+
|
|
27
|
+
//# sourceMappingURL=main.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"main.mjs","names":[],"sources":["../src/main.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { createFormancyMcpServer } from './server.js'\n\n/**\n * The executable. Reads the environment, wires the server, listens on stdio.\n *\n * A server is optional and its absence is a supported state: describe_spec,\n * validate_form and diff_forms need nothing but this process, so an agent can\n * author and check a whole form before anybody has deployed a backend. That is\n * deliberately the useful half.\n *\n * stdio rather than HTTP, because the client launches this process and talks\n * down its pipes. Nothing here listens on a port, so nothing here needs a\n * port's worth of thinking about who can reach it.\n */\nconst baseUrl = process.env['FORMANCY_URL']\nconst apiKey = process.env['FORMANCY_API_KEY']\n\nif ((baseUrl === undefined) !== (apiKey === undefined)) {\n // Half-configured is the state worth refusing: a URL with no key produces a\n // 401 on every call, and a key with no URL produces nothing at all. Both\n // look like the tool being broken rather than unconfigured.\n throw new Error(\n 'Set FORMANCY_URL and FORMANCY_API_KEY together, or neither. With neither, the local tools still work.',\n )\n}\n\nconst server = createFormancyMcpServer(\n baseUrl === undefined || apiKey === undefined ? {} : { access: { baseUrl, apiKey } },\n)\n\nawait server.connect(new StdioServerTransport())\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAM,UAAU,QAAQ,IAAI;AAC5B,MAAM,SAAS,QAAQ,IAAI;AAE3B,IAAK,YAAY,KAAA,OAAgB,WAAW,KAAA,IAI1C,MAAM,IAAI,MACR,uGACF;AAOF,MAJe,wBACb,YAAY,KAAA,KAAa,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ;CAAE;CAAS;AAAO,EAAE,CAG1E,CAAC,CAAC,QAAQ,IAAI,qBAAqB,CAAC"}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { authoringFacts, diffSchemas } from "@formancy/spec";
|
|
2
|
+
import { validateSchema } from "@formancy/spec/validate";
|
|
3
|
+
import { engineRefusal, expressionProblems } from "@formancy/core";
|
|
4
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
//#region src/tools.ts
|
|
7
|
+
/**
|
|
8
|
+
* Everything the spec allows, so a model does not have to guess.
|
|
9
|
+
*
|
|
10
|
+
* The cheapest tool here and probably the most valuable: without it a model
|
|
11
|
+
* invents `type: "phone"` or `type: "email"` from its memory of other form
|
|
12
|
+
* builders, gets a validation error, and burns a turn finding out that `text`
|
|
13
|
+
* with `format: "email"` is the answer. Told up front, it does not.
|
|
14
|
+
*/
|
|
15
|
+
function describeSpec() {
|
|
16
|
+
const facts = authoringFacts();
|
|
17
|
+
return {
|
|
18
|
+
ok: true,
|
|
19
|
+
summary: `formancy speaks spec versions ${facts.specVersions.join(" and ")}; new documents should use "${facts.currentSpecVersion}". A field type not in this list does not exist, whatever other form builders call it — an email field is type "text" with format "email".`,
|
|
20
|
+
data: facts
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Check a document without publishing it — the server's publish checks, in the
|
|
25
|
+
* gate's order. Only the analysis of regular-expression `pattern`s stays on
|
|
26
|
+
* the server: it needs an analysis engine this package does not carry, and the
|
|
27
|
+
* server's refusal names the pattern.
|
|
28
|
+
*
|
|
29
|
+
* Schema validity, the engine's compile and expression sanity are different
|
|
30
|
+
* failures with different fixes, and a later check means nothing in a document
|
|
31
|
+
* an earlier one has rejected. So the structure is checked first, then whether
|
|
32
|
+
* the engine would open the document at all, then whether its expressions
|
|
33
|
+
* would ever do anything.
|
|
34
|
+
*
|
|
35
|
+
* The middle check was once missing, and this tool told a model that a form
|
|
36
|
+
* with a misspelled field name was valid: the validator does not read CEL and
|
|
37
|
+
* the expression check skips what the engine refuses, so nothing here asked
|
|
38
|
+
* the engine. The server did, and refused it.
|
|
39
|
+
*/
|
|
40
|
+
function validateForm(document) {
|
|
41
|
+
const result = validateSchema(document);
|
|
42
|
+
if (!result.valid) return {
|
|
43
|
+
ok: false,
|
|
44
|
+
summary: `Not a valid formancy document: ${String(result.errors.length)} problem(s). Fix these before publishing.`,
|
|
45
|
+
data: {
|
|
46
|
+
valid: false,
|
|
47
|
+
errors: result.errors
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
const refusal = engineRefusal(document);
|
|
51
|
+
if (refusal !== void 0) return {
|
|
52
|
+
ok: false,
|
|
53
|
+
summary: "The document is structurally valid, but the engine refuses to open it — the same engine the server's publish gate and every renderer build, so this form could be neither published nor shown. " + refusal,
|
|
54
|
+
data: {
|
|
55
|
+
valid: true,
|
|
56
|
+
engineRefusal: refusal
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
const problems = expressionProblems(document);
|
|
60
|
+
if (problems.length > 0) return {
|
|
61
|
+
ok: false,
|
|
62
|
+
summary: `The document is structurally valid, but ${String(problems.length)} expression(s) will never do anything. These compile and then fail at evaluation, so nothing would report them at runtime: a computed field would stay empty and a visible rule would show the field it was meant to hide.`,
|
|
63
|
+
data: {
|
|
64
|
+
valid: true,
|
|
65
|
+
expressionProblems: problems
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
return {
|
|
69
|
+
ok: true,
|
|
70
|
+
summary: "Valid, and every expression type-checks.",
|
|
71
|
+
data: { valid: true }
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What a change does to the submissions already collected.
|
|
76
|
+
*
|
|
77
|
+
* The question an agent cannot answer by reading the two documents, and the
|
|
78
|
+
* one whose wrong answer is permanent. `breaking` is not advice.
|
|
79
|
+
*/
|
|
80
|
+
function diffForms(before, after) {
|
|
81
|
+
const first = validateSchema(before);
|
|
82
|
+
const second = validateSchema(after);
|
|
83
|
+
if (!first.valid || !second.valid) return {
|
|
84
|
+
ok: false,
|
|
85
|
+
summary: "Both documents have to be valid before they can be compared. Run validate_form on each.",
|
|
86
|
+
data: {
|
|
87
|
+
beforeValid: first.valid,
|
|
88
|
+
afterValid: second.valid
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const changes = diffSchemas(before, after);
|
|
92
|
+
const worst = severityOf(changes);
|
|
93
|
+
return {
|
|
94
|
+
ok: true,
|
|
95
|
+
summary: changes.length === 0 ? "No change: the two documents are identical once canonicalised." : `${String(changes.length)} change(s), worst severity ${worst}. ` + ADVICE[worst],
|
|
96
|
+
data: {
|
|
97
|
+
severity: worst,
|
|
98
|
+
changes
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const ADVICE = {
|
|
103
|
+
none: "",
|
|
104
|
+
compatible: "Existing drafts and submissions rebind silently.",
|
|
105
|
+
lossy: "Existing data rebinds, but some answers no longer have a field to live in. They are kept under data.__orphaned rather than deleted.",
|
|
106
|
+
breaking: "Existing drafts CANNOT rebind and will open read-only against the version that produced them. Say so before publishing, and consider a new form instead."
|
|
107
|
+
};
|
|
108
|
+
function severityOf(changes) {
|
|
109
|
+
if (changes.some((change) => change.severity === "breaking")) return "breaking";
|
|
110
|
+
if (changes.some((change) => change.severity === "lossy")) return "lossy";
|
|
111
|
+
if (changes.length > 0) return "compatible";
|
|
112
|
+
return "none";
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Publish, but check first.
|
|
116
|
+
*
|
|
117
|
+
* The local validation is not an optimisation. A model that gets a 422 back
|
|
118
|
+
* has to guess what the server meant from an error shape it has never seen;
|
|
119
|
+
* a model that gets `expressionProblems` back is told which rule, in which
|
|
120
|
+
* words, and what to write instead. And an invalid document never travels.
|
|
121
|
+
*/
|
|
122
|
+
async function publishForm(access, path, document) {
|
|
123
|
+
const checked = validateForm(document);
|
|
124
|
+
if (!checked.ok) return {
|
|
125
|
+
ok: false,
|
|
126
|
+
summary: `Not published, because the document would not have worked. ${checked.summary}`,
|
|
127
|
+
data: checked.data
|
|
128
|
+
};
|
|
129
|
+
return request(access, "/forms", {
|
|
130
|
+
method: "POST",
|
|
131
|
+
body: JSON.stringify({
|
|
132
|
+
path,
|
|
133
|
+
schema: document
|
|
134
|
+
})
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
async function listForms(access) {
|
|
138
|
+
return request(access, "/forms");
|
|
139
|
+
}
|
|
140
|
+
async function getForm(access, path) {
|
|
141
|
+
return request(access, `/f/${encodeURIComponent(path)}`);
|
|
142
|
+
}
|
|
143
|
+
async function listSubmissions(access, path) {
|
|
144
|
+
return request(access, `/f/${encodeURIComponent(path)}/submissions`);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* One request, and one place that knows how a failure is reported.
|
|
148
|
+
*
|
|
149
|
+
* Every error comes back as `ok: false` with the server's own words rather
|
|
150
|
+
* than as a thrown exception, because a thrown exception reaches a model as a
|
|
151
|
+
* stack trace and tells it nothing it can act on.
|
|
152
|
+
*/
|
|
153
|
+
async function request(access, route, init = {}) {
|
|
154
|
+
const send = access.fetch ?? globalThis.fetch;
|
|
155
|
+
const url = `${access.baseUrl.replace(/\/$/, "")}${route}`;
|
|
156
|
+
let response;
|
|
157
|
+
try {
|
|
158
|
+
response = await send(url, {
|
|
159
|
+
...init,
|
|
160
|
+
headers: {
|
|
161
|
+
...init.body === void 0 ? {} : { "content-type": "application/json" },
|
|
162
|
+
authorization: `Bearer ${access.apiKey}`,
|
|
163
|
+
...init.headers
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
} catch (error) {
|
|
167
|
+
return {
|
|
168
|
+
ok: false,
|
|
169
|
+
summary: `Could not reach the formancy server at ${access.baseUrl}: ${error instanceof Error ? error.message : String(error)}. Check FORMANCY_URL, and that the server is running.`
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
const body = await response.json().catch(() => void 0);
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
const detail = messageFrom(body);
|
|
175
|
+
return {
|
|
176
|
+
ok: false,
|
|
177
|
+
summary: response.status === 401 || response.status === 403 ? `The server refused the request (${String(response.status)}). Check FORMANCY_API_KEY.` : `The server refused the request (${String(response.status)})${detail === void 0 ? "." : `: ${detail}`}`,
|
|
178
|
+
...body === void 0 ? {} : { data: body }
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
summary: "Done.",
|
|
184
|
+
data: body
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
function messageFrom(body) {
|
|
188
|
+
if (body === null || typeof body !== "object") return void 0;
|
|
189
|
+
const record = body;
|
|
190
|
+
if (typeof record.message === "string") return record.message;
|
|
191
|
+
if (typeof record.error === "string") return record.error;
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/server.ts
|
|
195
|
+
/**
|
|
196
|
+
* Names and descriptions, apart from the wiring.
|
|
197
|
+
*
|
|
198
|
+
* Exported because the description is the prompt: it is the only thing telling
|
|
199
|
+
* a model when to reach for a tool, and a wrong one means a tool that is never
|
|
200
|
+
* called or called for the wrong reason. Kept where it can be read and tested
|
|
201
|
+
* rather than buried in a registration call.
|
|
202
|
+
*/
|
|
203
|
+
const TOOL_DEFINITIONS = {
|
|
204
|
+
describe_spec: "List every field type, layout kind, rule kind and format the formancy spec defines. Call this BEFORE writing a form document. A type not in the list does not exist, whatever other form builders call it.",
|
|
205
|
+
validate_form: "Run the server's publish checks without publishing: against the spec, through the engine that renders the form (a misspelled field name, a cycle between computed fields, a condition that is not certain to produce a bool), and for expressions that compile but can never evaluate — the failure that is silent at runtime. Each comes back separately, with what to change.",
|
|
206
|
+
diff_forms: "Compare two form documents and report what the change would do to submissions already collected: compatible, lossy, or breaking. Call this before publishing over an existing form.",
|
|
207
|
+
publish_form: "Publish a form document to a formancy server. Validates locally first and refuses to send an invalid document, so the reason comes back as something to fix rather than as a 422.",
|
|
208
|
+
list_forms: "List the forms on the formancy server, with their current version.",
|
|
209
|
+
get_form: "Fetch one form document from the formancy server, with its version and schema hash.",
|
|
210
|
+
list_submissions: "List submissions for one form."
|
|
211
|
+
};
|
|
212
|
+
/** MCP wants string content; a tool that answered with prose alone would throw
|
|
213
|
+
* away the part an agent can act on, so both travel. */
|
|
214
|
+
function respond(result) {
|
|
215
|
+
return {
|
|
216
|
+
content: [{
|
|
217
|
+
type: "text",
|
|
218
|
+
text: result.data === void 0 ? result.summary : `${result.summary}\n\n${JSON.stringify(result.data, null, 2)}`
|
|
219
|
+
}],
|
|
220
|
+
...result.ok ? {} : { isError: true }
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
/** A tool that needs a server, when there is not one. */
|
|
224
|
+
function noServer(name) {
|
|
225
|
+
return {
|
|
226
|
+
ok: false,
|
|
227
|
+
summary: `${name} needs a formancy server, and none is configured. Set FORMANCY_URL and FORMANCY_API_KEY. The local tools — describe_spec, validate_form and diff_forms — work without one, so a form can be written and checked before a server exists.`
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* The arguments each tool takes.
|
|
232
|
+
*
|
|
233
|
+
* A document arrives as `unknown` on purpose: it is checked by
|
|
234
|
+
* `validateSchema` against the spec's own JSON Schema, which is the one
|
|
235
|
+
* authority on what a formancy document is. Describing its shape a second
|
|
236
|
+
* time here in Zod would be a second authority, and the day the two disagree
|
|
237
|
+
* the tool would reject a document the product accepts.
|
|
238
|
+
*/
|
|
239
|
+
const DOCUMENT = z.unknown().describe("A formancy form document (the JSON schema object).");
|
|
240
|
+
const FORM_PATH = z.string().min(1).describe("The form's path, as it appears in its URL.");
|
|
241
|
+
function createFormancyMcpServer(options = {}) {
|
|
242
|
+
const server = new McpServer({
|
|
243
|
+
name: "formancy",
|
|
244
|
+
version: "0.1.0"
|
|
245
|
+
});
|
|
246
|
+
const { access } = options;
|
|
247
|
+
server.registerTool("describe_spec", { description: TOOL_DEFINITIONS.describe_spec }, () => respond(describeSpec()));
|
|
248
|
+
server.registerTool("validate_form", {
|
|
249
|
+
description: TOOL_DEFINITIONS.validate_form,
|
|
250
|
+
inputSchema: { document: DOCUMENT }
|
|
251
|
+
}, ({ document }) => respond(validateForm(document)));
|
|
252
|
+
server.registerTool("diff_forms", {
|
|
253
|
+
description: TOOL_DEFINITIONS.diff_forms,
|
|
254
|
+
inputSchema: {
|
|
255
|
+
before: DOCUMENT,
|
|
256
|
+
after: DOCUMENT
|
|
257
|
+
}
|
|
258
|
+
}, ({ before, after }) => respond(diffForms(before, after)));
|
|
259
|
+
server.registerTool("publish_form", {
|
|
260
|
+
description: TOOL_DEFINITIONS.publish_form,
|
|
261
|
+
inputSchema: {
|
|
262
|
+
path: FORM_PATH,
|
|
263
|
+
document: DOCUMENT
|
|
264
|
+
}
|
|
265
|
+
}, async ({ path, document }) => respond(access === void 0 ? noServer("publish_form") : await publishForm(access, path, document)));
|
|
266
|
+
server.registerTool("list_forms", { description: TOOL_DEFINITIONS.list_forms }, async () => respond(access === void 0 ? noServer("list_forms") : await listForms(access)));
|
|
267
|
+
server.registerTool("get_form", {
|
|
268
|
+
description: TOOL_DEFINITIONS.get_form,
|
|
269
|
+
inputSchema: { path: FORM_PATH }
|
|
270
|
+
}, async ({ path }) => respond(access === void 0 ? noServer("get_form") : await getForm(access, path)));
|
|
271
|
+
server.registerTool("list_submissions", {
|
|
272
|
+
description: TOOL_DEFINITIONS.list_submissions,
|
|
273
|
+
inputSchema: { path: FORM_PATH }
|
|
274
|
+
}, async ({ path }) => respond(access === void 0 ? noServer("list_submissions") : await listSubmissions(access, path)));
|
|
275
|
+
return server;
|
|
276
|
+
}
|
|
277
|
+
//#endregion
|
|
278
|
+
export { getForm as a, publishForm as c, diffForms as i, validateForm as l, createFormancyMcpServer as n, listForms as o, describeSpec as r, listSubmissions as s, TOOL_DEFINITIONS as t };
|
|
279
|
+
|
|
280
|
+
//# sourceMappingURL=server-CdcuxHHN.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server-CdcuxHHN.mjs","names":[],"sources":["../src/tools.ts","../src/server.ts"],"sourcesContent":["import { authoringFacts, diffSchemas } from '@formancy/spec'\nimport { validateSchema } from '@formancy/spec/validate'\nimport type { Change, FormSchema } from '@formancy/spec'\nimport { engineRefusal, expressionProblems } from '@formancy/core'\n\n/**\n * What formancy can be asked to do by a coding agent, as plain functions.\n *\n * Separated from the MCP server itself for the same reason `server-core` is separated\n * from `server`: a use-case that can only be exercised through a transport is one nobody\n * can test. Everything here is a function from JSON to JSON.\n *\n * **The tools check first and act second.** `publish_form` validates locally before it\n * opens a socket, so an invalid document never reaches the server and the model gets the\n * reason rather than a 422. That is possible because the format has a published JSON\n * Schema and the expressions are statically type-checked — a generated document is\n * checkable before anything is done with it.\n */\n\n/** A tool's answer: what happened, and what the agent should do about it. */\nexport interface ToolResult {\n /** False means the agent must fix something before trying again. */\n readonly ok: boolean\n /** Prose for the model. Written to be acted on, not logged. */\n readonly summary: string\n /** The machine-readable part, when there is one. */\n readonly data?: unknown\n}\n\n/** Where a formancy server is, and how to prove who you are to it. */\nexport interface ServerAccess {\n readonly baseUrl: string\n readonly apiKey: string\n /** Injected so tests do not need a socket. */\n readonly fetch?: typeof globalThis.fetch\n}\n\n// ---------------------------------------------------------------- local tools\n\n/**\n * Everything the spec allows, so a model does not have to guess.\n *\n * The cheapest tool here and probably the most valuable: without it a model\n * invents `type: \"phone\"` or `type: \"email\"` from its memory of other form\n * builders, gets a validation error, and burns a turn finding out that `text`\n * with `format: \"email\"` is the answer. Told up front, it does not.\n */\nexport function describeSpec(): ToolResult {\n const facts = authoringFacts()\n return {\n ok: true,\n summary:\n `formancy speaks spec versions ${facts.specVersions.join(' and ')}; new documents should ` +\n `use \"${facts.currentSpecVersion}\". A field type not in this list does not exist, whatever ` +\n `other form builders call it — an email field is type \"text\" with format \"email\".`,\n data: facts,\n }\n}\n\n/**\n * Check a document without publishing it — the server's publish checks, in the\n * gate's order. Only the analysis of regular-expression `pattern`s stays on\n * the server: it needs an analysis engine this package does not carry, and the\n * server's refusal names the pattern.\n *\n * Schema validity, the engine's compile and expression sanity are different\n * failures with different fixes, and a later check means nothing in a document\n * an earlier one has rejected. So the structure is checked first, then whether\n * the engine would open the document at all, then whether its expressions\n * would ever do anything.\n *\n * The middle check was once missing, and this tool told a model that a form\n * with a misspelled field name was valid: the validator does not read CEL and\n * the expression check skips what the engine refuses, so nothing here asked\n * the engine. The server did, and refused it.\n */\nexport function validateForm(document: unknown): ToolResult {\n const result = validateSchema(document)\n if (!result.valid) {\n return {\n ok: false,\n summary: `Not a valid formancy document: ${String(result.errors.length)} problem(s). Fix these before publishing.`,\n data: { valid: false, errors: result.errors },\n }\n }\n\n const refusal = engineRefusal(document as FormSchema)\n if (refusal !== undefined) {\n return {\n ok: false,\n summary:\n `The document is structurally valid, but the engine refuses to open it — the same engine the ` +\n `server's publish gate and every renderer build, so this form could be neither published nor shown. ` +\n refusal,\n data: { valid: true, engineRefusal: refusal },\n }\n }\n\n const problems = expressionProblems(document as FormSchema)\n if (problems.length > 0) {\n return {\n ok: false,\n summary:\n `The document is structurally valid, but ${String(problems.length)} expression(s) will never ` +\n `do anything. These compile and then fail at evaluation, so nothing would report them at runtime: ` +\n `a computed field would stay empty and a visible rule would show the field it was meant to hide.`,\n data: { valid: true, expressionProblems: problems },\n }\n }\n\n return {\n ok: true,\n summary: 'Valid, and every expression type-checks.',\n data: { valid: true },\n }\n}\n\n/**\n * What a change does to the submissions already collected.\n *\n * The question an agent cannot answer by reading the two documents, and the\n * one whose wrong answer is permanent. `breaking` is not advice.\n */\nexport function diffForms(before: unknown, after: unknown): ToolResult {\n const first = validateSchema(before)\n const second = validateSchema(after)\n if (!first.valid || !second.valid) {\n return {\n ok: false,\n summary: 'Both documents have to be valid before they can be compared. Run validate_form on each.',\n data: { beforeValid: first.valid, afterValid: second.valid },\n }\n }\n\n const changes = diffSchemas(before as FormSchema, after as FormSchema)\n const worst = severityOf(changes)\n\n return {\n ok: true,\n summary:\n changes.length === 0\n ? 'No change: the two documents are identical once canonicalised.'\n : `${String(changes.length)} change(s), worst severity ${worst}. ` + ADVICE[worst],\n data: { severity: worst, changes },\n }\n}\n\nconst ADVICE: Readonly<Record<'none' | 'compatible' | 'lossy' | 'breaking', string>> = {\n none: '',\n compatible: 'Existing drafts and submissions rebind silently.',\n lossy: 'Existing data rebinds, but some answers no longer have a field to live in. They are kept under data.__orphaned rather than deleted.',\n breaking:\n 'Existing drafts CANNOT rebind and will open read-only against the version that produced them. Say so before publishing, and consider a new form instead.',\n}\n\nfunction severityOf(changes: readonly Change[]): 'none' | 'compatible' | 'lossy' | 'breaking' {\n if (changes.some((change) => change.severity === 'breaking')) return 'breaking'\n if (changes.some((change) => change.severity === 'lossy')) return 'lossy'\n if (changes.length > 0) return 'compatible'\n return 'none'\n}\n\n// --------------------------------------------------------------- server tools\n\n/**\n * Publish, but check first.\n *\n * The local validation is not an optimisation. A model that gets a 422 back\n * has to guess what the server meant from an error shape it has never seen;\n * a model that gets `expressionProblems` back is told which rule, in which\n * words, and what to write instead. And an invalid document never travels.\n */\nexport async function publishForm(\n access: ServerAccess,\n path: string,\n document: unknown,\n): Promise<ToolResult> {\n const checked = validateForm(document)\n if (!checked.ok) {\n return {\n ok: false,\n summary: `Not published, because the document would not have worked. ${checked.summary}`,\n data: checked.data,\n }\n }\n\n return request(access, '/forms', {\n method: 'POST',\n body: JSON.stringify({ path, schema: document }),\n })\n}\n\nexport async function listForms(access: ServerAccess): Promise<ToolResult> {\n return request(access, '/forms')\n}\n\nexport async function getForm(access: ServerAccess, path: string): Promise<ToolResult> {\n return request(access, `/f/${encodeURIComponent(path)}`)\n}\n\nexport async function listSubmissions(access: ServerAccess, path: string): Promise<ToolResult> {\n return request(access, `/f/${encodeURIComponent(path)}/submissions`)\n}\n\n/**\n * One request, and one place that knows how a failure is reported.\n *\n * Every error comes back as `ok: false` with the server's own words rather\n * than as a thrown exception, because a thrown exception reaches a model as a\n * stack trace and tells it nothing it can act on.\n */\nasync function request(\n access: ServerAccess,\n route: string,\n init: RequestInit = {},\n): Promise<ToolResult> {\n const send = access.fetch ?? globalThis.fetch\n const url = `${access.baseUrl.replace(/\\/$/, '')}${route}`\n\n let response: Response\n try {\n response = await send(url, {\n ...init,\n headers: {\n ...(init.body === undefined ? {} : { 'content-type': 'application/json' }),\n authorization: `Bearer ${access.apiKey}`,\n ...init.headers,\n },\n })\n } catch (error) {\n return {\n ok: false,\n summary:\n `Could not reach the formancy server at ${access.baseUrl}: ${error instanceof Error ? error.message : String(error)}. ` +\n `Check FORMANCY_URL, and that the server is running.`,\n }\n }\n\n const body: unknown = await response.json().catch(() => undefined)\n\n if (!response.ok) {\n const detail = messageFrom(body)\n return {\n ok: false,\n summary:\n response.status === 401 || response.status === 403\n ? `The server refused the request (${String(response.status)}). Check FORMANCY_API_KEY.`\n : `The server refused the request (${String(response.status)})${detail === undefined ? '.' : `: ${detail}`}`,\n ...(body === undefined ? {} : { data: body }),\n }\n }\n\n return { ok: true, summary: 'Done.', data: body }\n}\n\nfunction messageFrom(body: unknown): string | undefined {\n if (body === null || typeof body !== 'object') return undefined\n const record = body as { message?: unknown; error?: unknown }\n if (typeof record.message === 'string') return record.message\n if (typeof record.error === 'string') return record.error\n return undefined\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { z } from 'zod'\nimport {\n describeSpec,\n diffForms,\n getForm,\n listForms,\n listSubmissions,\n publishForm,\n validateForm,\n} from './tools.js'\nimport type { ServerAccess, ToolResult } from './tools.js'\n\n/**\n * The tools, wired to the protocol.\n *\n * Thin on purpose: every one of these is a call into `tools.ts` and a\n * conversion of the answer into MCP's content shape. The logic is tested\n * without a protocol, because a use-case that can only be exercised through a\n * transport is a use-case nobody tests properly.\n */\n\nexport interface McpServerOptions {\n /**\n * Where a formancy server is, if there is one.\n *\n * Absent is a supported state and not a degraded one: the four local tools\n * — describe_spec, validate_form, diff_forms and the checking half of\n * publishing — need no server at all, which means an agent can author and\n * verify a whole form before anybody has deployed anything.\n */\n readonly access?: ServerAccess\n}\n\n/**\n * Names and descriptions, apart from the wiring.\n *\n * Exported because the description is the prompt: it is the only thing telling\n * a model when to reach for a tool, and a wrong one means a tool that is never\n * called or called for the wrong reason. Kept where it can be read and tested\n * rather than buried in a registration call.\n */\nexport const TOOL_DEFINITIONS = {\n describe_spec:\n 'List every field type, layout kind, rule kind and format the formancy spec defines. ' +\n 'Call this BEFORE writing a form document. A type not in the list does not exist, whatever ' +\n 'other form builders call it.',\n validate_form:\n \"Run the server's publish checks without publishing: against the spec, through the engine \" +\n 'that renders the form (a misspelled field name, a cycle between computed fields, a ' +\n 'condition that is not certain to produce a bool), and for expressions that compile but ' +\n 'can never evaluate — the failure that is silent at runtime. Each comes back separately, ' +\n 'with what to change.',\n diff_forms:\n 'Compare two form documents and report what the change would do to submissions already ' +\n 'collected: compatible, lossy, or breaking. Call this before publishing over an existing form.',\n publish_form:\n 'Publish a form document to a formancy server. Validates locally first and refuses to send ' +\n 'an invalid document, so the reason comes back as something to fix rather than as a 422.',\n list_forms: 'List the forms on the formancy server, with their current version.',\n get_form: 'Fetch one form document from the formancy server, with its version and schema hash.',\n list_submissions: 'List submissions for one form.',\n} as const\n\n/** MCP wants string content; a tool that answered with prose alone would throw\n * away the part an agent can act on, so both travel. */\nfunction respond(result: ToolResult): {\n content: { type: 'text'; text: string }[]\n isError?: boolean\n} {\n const text =\n result.data === undefined\n ? result.summary\n : `${result.summary}\\n\\n${JSON.stringify(result.data, null, 2)}`\n // `isError` rather than a thrown exception: a refusal is an answer the model\n // should read and act on, not a transport failure.\n return { content: [{ type: 'text', text }], ...(result.ok ? {} : { isError: true }) }\n}\n\n/** A tool that needs a server, when there is not one. */\nfunction noServer(name: string): ToolResult {\n return {\n ok: false,\n summary:\n `${name} needs a formancy server, and none is configured. Set FORMANCY_URL and ` +\n `FORMANCY_API_KEY. The local tools — describe_spec, validate_form and diff_forms — work ` +\n `without one, so a form can be written and checked before a server exists.`,\n }\n}\n\n/**\n * The arguments each tool takes.\n *\n * A document arrives as `unknown` on purpose: it is checked by\n * `validateSchema` against the spec's own JSON Schema, which is the one\n * authority on what a formancy document is. Describing its shape a second\n * time here in Zod would be a second authority, and the day the two disagree\n * the tool would reject a document the product accepts.\n */\nconst DOCUMENT = z.unknown().describe('A formancy form document (the JSON schema object).')\nconst FORM_PATH = z.string().min(1).describe(\"The form's path, as it appears in its URL.\")\n\nexport function createFormancyMcpServer(options: McpServerOptions = {}): McpServer {\n const server = new McpServer({ name: 'formancy', version: '0.1.0' })\n const { access } = options\n\n server.registerTool('describe_spec', { description: TOOL_DEFINITIONS.describe_spec }, () =>\n respond(describeSpec()),\n )\n\n server.registerTool(\n 'validate_form',\n { description: TOOL_DEFINITIONS.validate_form, inputSchema: { document: DOCUMENT } },\n ({ document }) => respond(validateForm(document)),\n )\n\n server.registerTool(\n 'diff_forms',\n {\n description: TOOL_DEFINITIONS.diff_forms,\n inputSchema: { before: DOCUMENT, after: DOCUMENT },\n },\n ({ before, after }) => respond(diffForms(before, after)),\n )\n\n server.registerTool(\n 'publish_form',\n {\n description: TOOL_DEFINITIONS.publish_form,\n inputSchema: { path: FORM_PATH, document: DOCUMENT },\n },\n async ({ path, document }) =>\n respond(\n access === undefined\n ? noServer('publish_form')\n : await publishForm(access, path, document),\n ),\n )\n\n server.registerTool('list_forms', { description: TOOL_DEFINITIONS.list_forms }, async () =>\n respond(access === undefined ? noServer('list_forms') : await listForms(access)),\n )\n\n server.registerTool(\n 'get_form',\n { description: TOOL_DEFINITIONS.get_form, inputSchema: { path: FORM_PATH } },\n async ({ path }) =>\n respond(access === undefined ? noServer('get_form') : await getForm(access, path)),\n )\n\n server.registerTool(\n 'list_submissions',\n { description: TOOL_DEFINITIONS.list_submissions, inputSchema: { path: FORM_PATH } },\n async ({ path }) =>\n respond(\n access === undefined ? noServer('list_submissions') : await listSubmissions(access, path),\n ),\n )\n\n return server\n}\n"],"mappings":";;;;;;;;;;;;;;AA+CA,SA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AE,MAAM,UAAU;CAAE,GACnF,OAAO,EAAE,WACP,QACE,WAAW,KAAA,IAAY,SAAS,kBAAkB,IAAI,MAAM,gBAAgB,QAAQ,IAAI,CAC1F,CACJ;CAEA,OAAO;AACT"}
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@formancy/mcp",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "formancy as tools for a coding agent: author a form, have it checked before it exists, and publish it.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"bin": {
|
|
9
|
+
"formancy-mcp": "./dist/main.mjs"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/index.d.mts",
|
|
14
|
+
"default": "./dist/index.mjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"dist",
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"NOTICE"
|
|
21
|
+
],
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@formancy/core": "0.2.0",
|
|
24
|
+
"@formancy/spec": "0.2.0",
|
|
25
|
+
"@modelcontextprotocol/sdk": "^1.30.1",
|
|
26
|
+
"zod": "^4.6.5"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
30
|
+
"publint": "^0.3.24",
|
|
31
|
+
"tsdown": "^0.23.0",
|
|
32
|
+
"typescript": "~6.0.3",
|
|
33
|
+
"vitest": "^5.0.1",
|
|
34
|
+
"@vitest/coverage-v8": "^5.0.1",
|
|
35
|
+
"@types/node": "^22.10.0"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"repository": {
|
|
41
|
+
"type": "git",
|
|
42
|
+
"url": "git+https://github.com/sharkysan/formancy.ai.git",
|
|
43
|
+
"directory": "packages/mcp"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/sharkysan/formancy.ai",
|
|
46
|
+
"bugs": "https://github.com/sharkysan/formancy.ai/issues",
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsdown",
|
|
49
|
+
"test:coverage": "vitest run --coverage",
|
|
50
|
+
"test": "vitest run",
|
|
51
|
+
"typecheck": "tsc --noEmit",
|
|
52
|
+
"check:pkg": "publint && attw --pack . --profile esm-only"
|
|
53
|
+
}
|
|
54
|
+
}
|