@wyattjoh/rfc 0.1.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/src/mcp.ts ADDED
@@ -0,0 +1,476 @@
1
+ import {
2
+ CitationVerificationResultSchema,
3
+ EvidenceBundleSchema,
4
+ InvalidInputError,
5
+ RfcSourceCacheRemoveResultSchema,
6
+ RfcSourceCacheStatusSchema,
7
+ datatrackerTopicSearchTermLimit,
8
+ datatrackerTopicSearchTermMaximumCharacters,
9
+ schemaVersion,
10
+ } from "@wyattjoh/rfc-core";
11
+ import { McpServer, type CallToolResult } from "@modelcontextprotocol/server";
12
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
13
+ import { Schema } from "effect";
14
+ import { AuthStatusSchema } from "./credentials";
15
+ import {
16
+ executeAuthStatus,
17
+ executeCitationVerification,
18
+ executeResearch,
19
+ executeSourceCacheRemove,
20
+ executeSourceCacheStatus,
21
+ renderAuthStatus,
22
+ renderCitationVerification,
23
+ renderEvidenceBundle,
24
+ renderSourceCacheRemove,
25
+ renderSourceCacheStatus,
26
+ toRfcOperationErrorEnvelope,
27
+ type RfcOperationDependencies,
28
+ type RfcOperationOptions,
29
+ type RfcOperationResult,
30
+ type RfcOperationWarning,
31
+ } from "./operations";
32
+
33
+ /**
34
+ * Static URI for the complete model-facing RFC workflow reference.
35
+ */
36
+ export const rfcMcpAgentReferenceUri = "rfc://docs/agent-workflow" as const;
37
+
38
+ /**
39
+ * Cross-tool instructions advertised during MCP initialization.
40
+ */
41
+ export const rfcMcpInstructions = `For an ordinary known-RFC answer, call research_known_rfc exactly once, then answer and stop. Do not call verify_citation after research to re-check returned evidence, including when status is needs_review. Do not run preflight tools. Do not read the agent-workflow resource.
42
+
43
+ Use this server as the complete backend for published IETF RFC questions. Do not answer RFC claims from memory or another provider. When the RFC identifier is unknown, call research_topic with { question, searchTerms } using one to four deliberate ordered technical terms. Use verify_citation only when the user supplied a quotation or explicitly requested a distinct paraphrase check.
44
+
45
+ For one simple atomic question, call one research tool once. Only when that result contains neither usable accepted evidence nor a review candidate may you make at most one targeted follow-up research call. Do not rephrase valid results to chase answered status or higher confidence. For up to two explicit independent questions, keep them as separate research calls; do not invent a split for an ambiguous request.
46
+
47
+ Topic search terms are transmitted verbatim in Datatracker URLs and may appear in upstream logs; never derive hidden terms or send the full question as a search term unless the user explicitly chose it.
48
+
49
+ Preserve research status exactly: answered, partial, unsupported, needs_review, or needs_split. Accepted evidence may support an answer. A review candidate is canonical but unaccepted and must be quoted only as qualified review material. Keep requested and current RFC contexts distinct and never silently substitute a successor.
50
+
51
+ Exact reproduction of accepted evidence needs no citation call. Verify at most two paraphrased claims once each with verify_citation, using the exact returned quote and its UTF-8 byte offset. If a direct verification verdict is fabricated, use at most one research call to locate current wording and one verification call for that replacement. Never guess wording or offsets. Unsupported, contradicted, or fabricated verdicts cannot support an unqualified claim.
52
+
53
+ Operational tool errors are not research statuses. Preserve their typed error code and stop rather than substituting stale text, another provider, or memory. If a tool error reports a missing credential, ask the human operator to run rfc auth add; never request or accept the secret through MCP. A usage-accounting warning follows a successful paid operation and must not trigger a retry.
54
+
55
+ Do not read the agent-workflow resource for ordinary research. Read ${rfcMcpAgentReferenceUri} only when handling a non-answer status, operational failure, citation-repair workflow, or a provenance, privacy, cost, or cache question.`;
56
+
57
+ /**
58
+ * Complete Markdown reference exposed as a static MCP resource.
59
+ */
60
+ export const rfcMcpAgentReference = `# RFC MCP agent workflow
61
+
62
+ This MCP server is the complete RFC research backend. It owns live RFC discovery, RFC currency traversal, canonical RFC Editor source retrieval, bounded evidence selection, citation verification, source caching, provider credential status, and usage accounting. Do not answer RFC claims from memory or another provider.
63
+
64
+ ## Bounded workflow
65
+
66
+ For one atomic question:
67
+
68
+ 1. Call \`research_known_rfc\` when the RFC is known, otherwise call \`research_topic\` with one to four deliberate ordered technical search terms.
69
+ 2. Make at most one targeted follow-up research call, and only when the first result has neither usable accepted evidence nor a review candidate. Never loop by rephrasing a valid result to chase \`answered\` or higher confidence.
70
+ 3. When accepted evidence or a review candidate is returned, answer from that result and stop. Quote accepted evidence unchanged with provenance. Quote a review candidate only as explicitly unaccepted or \`needs_review\`.
71
+ 4. Never call \`verify_citation\` after research to re-check returned evidence, normalize formatting, or obtain alternate provenance. Use it only for a user-supplied quotation or an explicitly requested distinct paraphrase check, at most twice.
72
+ 5. Stop after the budget. Preserve non-answer statuses and typed operational failures.
73
+
74
+ For up to two explicit independently answerable questions, use one research call per question and keep their inputs and outputs separate. Do not invent a split for an ambiguous request; preserve \`needs_split\`.
75
+
76
+ ## Tools
77
+
78
+ ### research_known_rfc
79
+
80
+ Research one atomic question against a known published RFC. The server performs bounded live metadata lookup and currency traversal, researches requested and applicable current RFC contexts independently, and never silently substitutes a successor.
81
+
82
+ Inputs are \`question\` and \`rfc\`. Use the exact RFC identifier, such as \`RFC9110\`.
83
+
84
+ ### research_topic
85
+
86
+ Discover and research published RFCs for one atomic topic question. Inputs are \`question\` and \`searchTerms\`. Supply one to four ordered non-empty terms, each no longer than ${datatrackerTopicSearchTermMaximumCharacters} characters. Terms are transmitted verbatim in Datatracker query URLs and may appear in diagnostics, errors, and upstream access logs. Do not generate hidden terms, rewrite the caller's phrases, or send the natural-language question upstream unless it was explicitly chosen as a term.
87
+
88
+ ### verify_citation
89
+
90
+ Verify one factual claim against one exact RFC quotation. Inputs are \`rfc\`, \`claim\`, \`quote\`, and optional \`offset\`. The offset is an absolute UTF-8 byte offset into the exact source identified by \`sourceHash\`, not a JavaScript string index. Copy it from research provenance or omit it for a unique quotation. Never guess wording or offsets.
91
+
92
+ ### source_cache_status
93
+
94
+ Inspect one named RFC source-cache entry without network access.
95
+
96
+ ### source_cache_remove
97
+
98
+ Remove one named RFC source-cache entry without network access. This destructive, idempotent tool requires \`confirm: true\`. There is no list-all, refresh-all, prefetch, bulk download, or bulk clear operation.
99
+
100
+ ### auth_status
101
+
102
+ Report only whether the stable TypeSafe credential identity is configured. The MCP never accepts, returns, adds, or removes credentials. If missing, ask the human operator to run \`rfc auth add\` outside MCP.
103
+
104
+ ## Research statuses
105
+
106
+ - \`answered\`: accepted direct evidence with no disqualifying uncertainty.
107
+ - \`partial\`: only part of the question or RFC currency coverage is established.
108
+ - \`unsupported\`: bounded research found no accepted answering evidence.
109
+ - \`needs_review\`: confidence is low, evidence conflicts, discovery is empty, or RFC currency is uncertain.
110
+ - \`needs_split\`: the question is compound and requires atomic questions.
111
+
112
+ A valid non-answer status is a successful tool result, not an operational failure. Review candidates are canonical source passages surfaced for bounded review but are not accepted evidence. Never turn them into unqualified claims.
113
+
114
+ ## Citation verdicts
115
+
116
+ - \`verified\`: the exact present quotation supports the claim.
117
+ - \`unsupported\`: the quotation does not establish the claim.
118
+ - \`contradicted\`: the quotation conflicts with the claim.
119
+ - \`fabricated\`: the supplied quotation is absent from the authoritative source.
120
+
121
+ Only accepted research evidence or a \`verified\` citation supports an unqualified factual claim. If a quote is fabricated, make at most one research call to locate current wording and at most one verification call for that replacement.
122
+
123
+ ## Provenance and RFC currency
124
+
125
+ Preserve exact quotes, RFC identifiers, requested/current context roles, relationship paths, nullable section labels, canonical source URLs, source hashes, \`offsetUnit: "utf8-byte"\`, and byte offsets. Do not answer a question about the requested RFC with current-context evidence without explicitly explaining the distinction.
126
+
127
+ ## Fail-closed operations
128
+
129
+ Operational failures are returned as MCP tool errors containing the safe version-two RFC error envelope. Report the code and stop. In particular:
130
+
131
+ - \`invalid_input\`: correct the bounded tool input.
132
+ - \`credential_missing\`: ask the human to run \`rfc auth add\`.
133
+ - \`credential_store_unavailable\` or \`credential_access_denied\`: ask the human to unlock or authorize the OS credential store; never use plaintext fallback.
134
+ - \`discovery_failed\`: report the Datatracker failure; do not invent or use stale metadata.
135
+ - \`source_cache_failed\`, \`source_fetch_failed\`, or \`source_revalidation_failed\`: report the authoritative source failure; never serve stale text or substitute another representation.
136
+ - \`rfc_not_found\`: correct the exact identifier or use topic discovery with explicit terms.
137
+ - \`decision_model_failed\`: report the bounded provider failure; do not switch provider or model.
138
+ - \`citation_quote_ambiguous\` or \`citation_offset_mismatch\`: copy an exact research offset or stop; never guess.
139
+ - \`internal_error\` or \`configuration_error\`: report an operational failure rather than asserting an answer.
140
+
141
+ ## Privacy, cost, and cache behavior
142
+
143
+ Questions and model responses are request-local and are not persisted. Topic search terms are sent to Datatracker and can be retained in upstream logs. Canonical RFC Editor text is cached per RFC with integrity and validator metadata. Fresh entries are reused; stale entries must revalidate successfully.
144
+
145
+ Research and citation results report provider input tokens and estimated input cost. A null estimate means unavailable, not zero. Each successful semantic operation updates per-user usage totals. If accounting fails, the tool still succeeds and adds a \`usage_accounting_failed\` warning; do not retry a successful paid operation because of that warning.
146
+ `;
147
+
148
+ const describedString = (description: string) =>
149
+ Schema.NonEmptyString.pipe(Schema.annotate({ description }));
150
+
151
+ const KnownRfcResearchInputSchema = Schema.Struct({
152
+ question: describedString("One independently answerable RFC question"),
153
+ rfc: describedString("Exact published RFC identifier, for example RFC9110"),
154
+ });
155
+
156
+ const TopicSearchTermSchema = Schema.String.check(
157
+ Schema.isMinLength(1),
158
+ Schema.isMaxLength(datatrackerTopicSearchTermMaximumCharacters),
159
+ ).pipe(
160
+ Schema.annotate({
161
+ description:
162
+ "Deliberate topic-discovery term sent verbatim in Datatracker query URLs and upstream logs",
163
+ }),
164
+ );
165
+
166
+ const TopicResearchInputSchema = Schema.Struct({
167
+ question: describedString("One independently answerable topic question"),
168
+ searchTerms: Schema.Array(TopicSearchTermSchema)
169
+ .check(Schema.isMinLength(1), Schema.isMaxLength(datatrackerTopicSearchTermLimit))
170
+ .pipe(
171
+ Schema.annotate({
172
+ description: "One to four ordered topic-discovery terms; preserve caller order",
173
+ }),
174
+ ),
175
+ });
176
+
177
+ const CitationInputSchema = Schema.Struct({
178
+ rfc: describedString("Exact published RFC identifier containing the quotation"),
179
+ claim: describedString("One factual claim to check"),
180
+ quote: describedString("Exact unchanged RFC quotation"),
181
+ offset: Schema.optionalKey(
182
+ Schema.Natural.pipe(
183
+ Schema.annotate({
184
+ description:
185
+ "Absolute UTF-8 byte offset copied from research provenance; omit for a unique quotation",
186
+ }),
187
+ ),
188
+ ),
189
+ });
190
+
191
+ const RfcInputSchema = Schema.Struct({
192
+ rfc: describedString("Exact named RFC source-cache entry, for example RFC9110"),
193
+ });
194
+
195
+ const SourceCacheRemoveInputSchema = Schema.Struct({
196
+ rfc: describedString("Exact named RFC source-cache entry, for example RFC9110"),
197
+ confirm: Schema.Literal(true).pipe(
198
+ Schema.annotate({ description: "Must be true to confirm removal of the named cache entry" }),
199
+ ),
200
+ });
201
+
202
+ const EmptyInputSchema = Schema.Struct({});
203
+
204
+ const toMcpSchema = <S extends Schema.ConstraintDecoder<unknown> & Schema.Constraint>(
205
+ schema: S,
206
+ ) => {
207
+ const validation = Schema.toStandardSchemaV1(schema);
208
+ const jsonSchema = Schema.toStandardJSONSchemaV1(schema);
209
+ return {
210
+ ...validation,
211
+ "~standard": {
212
+ ...validation["~standard"],
213
+ jsonSchema: jsonSchema["~standard"].jsonSchema,
214
+ },
215
+ };
216
+ };
217
+
218
+ const warningContent = (warnings: ReadonlyArray<RfcOperationWarning>) =>
219
+ warnings.map((warning) => ({ type: "text" as const, text: JSON.stringify(warning) }));
220
+
221
+ const semanticSuccess = <A extends object>(
222
+ result: RfcOperationResult<A>,
223
+ render: (value: A) => string,
224
+ ): CallToolResult => ({
225
+ content: [{ type: "text", text: render(result.value) }, ...warningContent(result.warnings)],
226
+ structuredContent: result.value,
227
+ });
228
+
229
+ const plainSuccess = <A extends object>(
230
+ value: A,
231
+ render: (value: A) => string,
232
+ ): CallToolResult => ({
233
+ content: [{ type: "text", text: render(value) }],
234
+ structuredContent: value,
235
+ });
236
+
237
+ const toolError = (error: unknown): CallToolResult => ({
238
+ content: [{ type: "text", text: JSON.stringify(toRfcOperationErrorEnvelope(error)) }],
239
+ isError: true,
240
+ });
241
+
242
+ /**
243
+ * Construct one self-describing RFC MCP server instance.
244
+ *
245
+ * @param options Trusted startup configuration that tool callers cannot override.
246
+ * @param dependencies Injectable credential, usage, and RFC-client boundaries.
247
+ * @returns An unconnected MCP server with tools and the agent reference registered.
248
+ */
249
+ export const createRfcMcpServer = (
250
+ options: RfcOperationOptions,
251
+ dependencies: RfcOperationDependencies,
252
+ ): McpServer => {
253
+ const server = new McpServer(
254
+ { name: "rfc", version: "0.1.0" },
255
+ { instructions: rfcMcpInstructions },
256
+ );
257
+
258
+ server.registerResource(
259
+ "agent_workflow",
260
+ rfcMcpAgentReferenceUri,
261
+ {
262
+ title: "RFC MCP agent workflow",
263
+ description:
264
+ "Reference for non-answer statuses, failures, citation repair, provenance, privacy, cache, and cost; skip for ordinary research",
265
+ mimeType: "text/markdown",
266
+ },
267
+ async (uri) => ({
268
+ contents: [
269
+ {
270
+ uri: uri.href,
271
+ mimeType: "text/markdown",
272
+ text: rfcMcpAgentReference,
273
+ },
274
+ ],
275
+ }),
276
+ );
277
+
278
+ server.registerTool(
279
+ "research_known_rfc",
280
+ {
281
+ title: "Research a known RFC",
282
+ description:
283
+ "Inputs: question, rfc. Research one atomic question against a known published RFC. If evidence or a review candidate is returned, answer from it without a verification call. Includes bounded RFC currency traversal, provenance, status, and diagnostics.",
284
+ inputSchema: toMcpSchema(KnownRfcResearchInputSchema),
285
+ outputSchema: toMcpSchema(EvidenceBundleSchema),
286
+ annotations: {
287
+ readOnlyHint: false,
288
+ destructiveHint: false,
289
+ idempotentHint: false,
290
+ openWorldHint: true,
291
+ },
292
+ },
293
+ async ({ question, rfc }) => {
294
+ try {
295
+ return semanticSuccess(
296
+ await executeResearch({ schemaVersion, question, rfc }, options, dependencies),
297
+ renderEvidenceBundle,
298
+ );
299
+ } catch (error) {
300
+ return toolError(error);
301
+ }
302
+ },
303
+ );
304
+
305
+ server.registerTool(
306
+ "research_topic",
307
+ {
308
+ title: "Discover and research RFCs",
309
+ description:
310
+ "Inputs: question, searchTerms (1-4). Research one atomic topic question. If evidence or a review candidate is returned, answer from it without a verification call. Terms are sent verbatim to Datatracker; results include provenance, status, and diagnostics.",
311
+ inputSchema: toMcpSchema(TopicResearchInputSchema),
312
+ outputSchema: toMcpSchema(EvidenceBundleSchema),
313
+ annotations: {
314
+ readOnlyHint: false,
315
+ destructiveHint: false,
316
+ idempotentHint: false,
317
+ openWorldHint: true,
318
+ },
319
+ },
320
+ async ({ question, searchTerms }) => {
321
+ try {
322
+ return semanticSuccess(
323
+ await executeResearch(
324
+ { schemaVersion, question, rfc: null, searchTerms },
325
+ options,
326
+ dependencies,
327
+ ),
328
+ renderEvidenceBundle,
329
+ );
330
+ } catch (error) {
331
+ return toolError(error);
332
+ }
333
+ },
334
+ );
335
+
336
+ server.registerTool(
337
+ "verify_citation",
338
+ {
339
+ title: "Verify an RFC citation",
340
+ description:
341
+ "Inputs: rfc, claim, quote; optional offset. Check one factual claim against one exact RFC quotation. Returns a verified, unsupported, contradicted, or fabricated verdict with canonical provenance.",
342
+ inputSchema: toMcpSchema(CitationInputSchema),
343
+ outputSchema: toMcpSchema(CitationVerificationResultSchema),
344
+ annotations: {
345
+ readOnlyHint: false,
346
+ destructiveHint: false,
347
+ idempotentHint: false,
348
+ openWorldHint: true,
349
+ },
350
+ },
351
+ async ({ rfc, claim, quote, offset }) => {
352
+ try {
353
+ return semanticSuccess(
354
+ await executeCitationVerification(
355
+ { schemaVersion, rfc, claim, quote, offset: offset ?? null },
356
+ options,
357
+ dependencies,
358
+ ),
359
+ renderCitationVerification,
360
+ );
361
+ } catch (error) {
362
+ return toolError(error);
363
+ }
364
+ },
365
+ );
366
+
367
+ server.registerTool(
368
+ "source_cache_status",
369
+ {
370
+ title: "Inspect an RFC source cache entry",
371
+ description:
372
+ "Input: rfc. Inspect one named canonical RFC source-cache entry locally without network access.",
373
+ inputSchema: toMcpSchema(RfcInputSchema),
374
+ outputSchema: toMcpSchema(RfcSourceCacheStatusSchema),
375
+ annotations: {
376
+ readOnlyHint: true,
377
+ destructiveHint: false,
378
+ idempotentHint: true,
379
+ openWorldHint: false,
380
+ },
381
+ },
382
+ async ({ rfc }) => {
383
+ try {
384
+ return plainSuccess(
385
+ await executeSourceCacheStatus(rfc, options, dependencies),
386
+ renderSourceCacheStatus,
387
+ );
388
+ } catch (error) {
389
+ return toolError(error);
390
+ }
391
+ },
392
+ );
393
+
394
+ server.registerTool(
395
+ "source_cache_remove",
396
+ {
397
+ title: "Remove an RFC source cache entry",
398
+ description:
399
+ "Inputs: rfc, confirm=true. Remove one named canonical RFC source-cache entry locally without network access; never performs bulk removal.",
400
+ inputSchema: toMcpSchema(SourceCacheRemoveInputSchema),
401
+ outputSchema: toMcpSchema(RfcSourceCacheRemoveResultSchema),
402
+ annotations: {
403
+ readOnlyHint: false,
404
+ destructiveHint: true,
405
+ idempotentHint: true,
406
+ openWorldHint: false,
407
+ },
408
+ },
409
+ async ({ rfc, confirm }) => {
410
+ try {
411
+ // The schema already requires `confirm: true`, but this is the only
412
+ // destructive operation on the surface and its enforcement must not
413
+ // rest entirely on the SDK validating before dispatch.
414
+ if (confirm !== true) {
415
+ throw new InvalidInputError({
416
+ reason: "Removing a source-cache entry requires confirm: true",
417
+ });
418
+ }
419
+ return plainSuccess(
420
+ await executeSourceCacheRemove(rfc, options, dependencies),
421
+ renderSourceCacheRemove,
422
+ );
423
+ } catch (error) {
424
+ return toolError(error);
425
+ }
426
+ },
427
+ );
428
+
429
+ server.registerTool(
430
+ "auth_status",
431
+ {
432
+ title: "Inspect RFC provider credential status",
433
+ description:
434
+ "No inputs. Report only whether the stable TypeSafe credential identity is configured. Never returns, accepts, adds, or removes the credential.",
435
+ inputSchema: toMcpSchema(EmptyInputSchema),
436
+ outputSchema: toMcpSchema(AuthStatusSchema),
437
+ annotations: {
438
+ readOnlyHint: true,
439
+ destructiveHint: false,
440
+ idempotentHint: true,
441
+ openWorldHint: false,
442
+ },
443
+ },
444
+ async () => {
445
+ try {
446
+ return plainSuccess(await executeAuthStatus(dependencies), renderAuthStatus);
447
+ } catch (error) {
448
+ return toolError(error);
449
+ }
450
+ },
451
+ );
452
+
453
+ return server;
454
+ };
455
+
456
+ /**
457
+ * Serve the RFC MCP over process standard input and output until the client disconnects.
458
+ *
459
+ * @param options Trusted startup configuration that tool callers cannot override.
460
+ * @param dependencies Injectable credential, usage, and RFC-client boundaries.
461
+ * @param reportError Out-of-band error reporter; production writes only to stderr.
462
+ * @returns A promise that resolves when the MCP connection closes.
463
+ */
464
+ export const runRfcMcpServer = async (
465
+ options: RfcOperationOptions,
466
+ dependencies: RfcOperationDependencies,
467
+ reportError: (error: Error) => void,
468
+ ): Promise<void> => {
469
+ const server = createRfcMcpServer(options, dependencies);
470
+ const closed = new Promise<void>((resolve) => {
471
+ server.server.onclose = resolve;
472
+ server.server.onerror = reportError;
473
+ });
474
+ await server.connect(new StdioServerTransport());
475
+ await closed;
476
+ };