@wyattjoh/rfc 0.4.1 → 0.5.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/README.md CHANGED
@@ -16,6 +16,7 @@ The model-facing tools are:
16
16
 
17
17
  - `rfc_research`
18
18
  - `rfc_verify_citation`
19
+ - `rfc_source_text`
19
20
  - `rfc_source_cache_status`
20
21
  - `rfc_source_cache_remove`
21
22
  - `rfc_auth_status`
@@ -63,6 +64,8 @@ Retrieval then makes three kinds of TypeSafe Jev requests. One request ranks the
63
64
 
64
65
  The result is a `research_result` whose `answers` hold, per question, `found`, the `searched` RFC identifiers, and ranked `hits`. Each hit carries the `rfc` document, its `role` (`requested`, `current`, or `discovered`), `relevance`, an overall `verdict`, and its `passages`. Each passage contains an exact paragraph `quote`, a nullable section heading, its selection `probability`, a `verdict` (`supports`, `partial`, `says_nothing`, or `contradicts`), and provenance with absolute UTF-8 byte offsets into the SHA-256 source, the declared `offsetUnit: "utf8-byte"`, the canonical URL, and the fetch time. Paragraphs never include page furniture; a paragraph interrupted by a page break is returned as two paragraphs. When `rfcs` were supplied, `currency` holds one `{ requested, current, complete, paths }` report per named RFC: its current successors and the relationship path to each, with `complete: false` when a successor was unresolved or cut off by a traversal bound (agent output then appends "(incomplete: some successors were not fetched)"), so a `current` hit is never silently substituted for the RFC the caller named. Human output prints one line per passage naming the RFC, section, verdict, relevance, and `current successor` when applicable, followed by the quote and its byte range.
65
66
 
67
+ When full RFC text is explicitly required or requested, use `rfc source-text RFC9110 --format json` or `rfc_source_text` instead of relying on research excerpts. With just `rfc`, the tool returns the canonical URL, source hash, total byte length, and parsed section headings with half-open UTF-8 byte ranges; it returns no text. Supply both `--start-offset` and `--end-offset` (or `startOffset` and `endOffset` in MCP/Pi) to read the exact, untruncated `[startOffset,endOffset)` slice. Use `--expected-source-hash` (or `expectedSourceHash`) on later requests to reject revalidated text that differs from the initial snapshot. Citation offsets use the same byte unit. Prefer research and citation tools unless full source text is explicitly necessary. This operation needs no TypeSafe credential and makes no provider call.
68
+
66
69
  Requested RFC Editor plain text is cached individually with its canonical URL, integrity hash, ETag, and HTTP freshness deadline. Fresh text is reused without a network request. Stale text is conditionally revalidated and is never used when authoritative revalidation fails. `rfc cache status RFC9110` reports a local hit or miss, while `rfc cache remove RFC9110` removes only that named entry; `--rfc RFC9110` remains an equivalent flag form. Neither command performs network access, and no bulk cache command is provided. Source retrieval accepts only a `200` body with an explicit `text/plain` Content-Type or a `304` conditional response, enforces one ten-second deadline across the complete operation, and rejects bodies above 8 MiB while streaming. A named RFC whose source cannot be loaded fails the request; a successor or topic hit whose source cannot be fetched is dropped.
67
70
 
68
71
  Research diagnostics report the policy version, requested and resolved models, usage and estimated cost, per-stage timings (`metadataMs`, `sourceMs`, `rankMs`, `sectionMs`, `paragraphMs`, `totalMs`), the candidate pool and ranked counts, and a retrieval trace with full upstream URLs, attempts and statuses, the source-cache outcome, and traversal bounds. Topic traces distinguish `upstreamRows`, deduplicated `uniqueCandidates`, the 32-document `mergeLimit`, `semanticCandidates` sent to TypeSafe, and `selectedSources` loaded from the RFC Editor. Public RFC documents omit relationship fields. Topic discovery accepts each bounded first page and reports `topicTruncated: true` when Datatracker advertises additional rows or the deterministic merge reaches its cap; it never follows unbounded pagination.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wyattjoh/rfc",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Agent-facing CLI and MCP server for evidence-grounded IETF RFC research.",
5
5
  "keywords": [
6
6
  "cli",
@@ -40,7 +40,7 @@
40
40
  "dependencies": {
41
41
  "@effect/platform-node": "4.0.0-rc.117",
42
42
  "@modelcontextprotocol/server": "2.0.0",
43
- "@wyattjoh/rfc-core": "0.2.1",
43
+ "@wyattjoh/rfc-core": "0.3.0",
44
44
  "effect": "4.0.0-rc.117"
45
45
  },
46
46
  "devDependencies": {
@@ -25,7 +25,7 @@ const rfcAgentInstructions = (surface: "mcp" | "pi"): string =>
25
25
  [
26
26
  `Answer published IETF RFC questions only from ${surface === "mcp" ? "this server" : "these tools"}, never from memory or another provider. Make one rfc_research call per user request, with each fact you need as its own entry in questions. Pass rfcs when you know the RFC numbers and searchTerms otherwise; both may be combined.`,
27
27
  "Answer from the returned passages and cite only the RFC and section shown. A passage marked current successor comes from the RFC that replaced the one named; say so rather than attributing it to the named RFC.",
28
- "When a question is not found, you may make one follow-up rfc_research call with other rfcs or searchTerms; RFC titles often differ from common names. Never re-research or re-verify returned passages. Use rfc_verify_citation only for a user-supplied quotation or an explicitly requested check.",
28
+ "When a question is not found, you may make one follow-up rfc_research call with other rfcs or searchTerms; RFC titles often differ from common names. Never re-research or re-verify returned passages. Use rfc_verify_citation only for a user-supplied quotation or an explicitly requested check. Use rfc_source_text only when the full RFC text is explicitly required or requested; prefer research and citation tools otherwise.",
29
29
  `Tool errors are final: keep the typed error code and stop; never substitute memory or another provider. For a missing credential, ask the human operator to run rfc auth login; never request or accept the secret${surface === "mcp" ? " through MCP" : ""}. Never retry a successful paid call over a usage-accounting warning.`,
30
30
  ...(surface === "mcp"
31
31
  ? [
@@ -63,6 +63,14 @@ export const rfcAgentParameterDescriptions = {
63
63
  quote: "Exact unchanged RFC quotation",
64
64
  offset:
65
65
  "Absolute UTF-8 byte offset copied from a research quote range; omit for a unique quotation",
66
+ sourceRfc:
67
+ "Exact published RFC identifier whose authoritative source text is requested, for example RFC9110",
68
+ sourceStart:
69
+ "Inclusive absolute UTF-8 byte offset; give both startOffset and endOffset to read text",
70
+ sourceEnd:
71
+ "Exclusive absolute UTF-8 byte offset, as in citation provenance; give both offsets to read text",
72
+ expectedSourceHash:
73
+ "Hash from an earlier source-text response; reject a changed source instead of mixing pages",
66
74
  cacheRfc: "Exact named RFC source-cache entry, for example RFC9110",
67
75
  confirm: "Must be true to confirm removal of the named cache entry",
68
76
  } as const;
@@ -106,6 +114,13 @@ export const rfcAgentToolMetadata = {
106
114
  "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. Verify at most two paraphrased claims, once each, using the exact returned quote and its UTF-8 byte offset; never guess wording or offsets. If a direct verification verdict is fabricated, use at most one research call to locate current wording and one verification call for that replacement. Unsupported, contradicted, or fabricated verdicts cannot support an unqualified claim.",
107
115
  annotations: rfcAgentToolAnnotations.semantic,
108
116
  },
117
+ sourceText: {
118
+ name: "rfc_source_text",
119
+ title: "Read authoritative RFC source text",
120
+ description:
121
+ "Input: rfc; optional startOffset and endOffset (both required for text), expectedSourceHash. Without offsets, returns source hash, total UTF-8 bytes, and parsed headings with half-open byte ranges, not text. With offsets, returns the exact untruncated [startOffset,endOffset) source slice; ranges can be copied from citations. Pass expectedSourceHash on later reads to reject changed sources. Use only when full RFC text is explicitly required or requested; prefer rfc_research and rfc_verify_citation otherwise.",
122
+ annotations: rfcAgentToolAnnotations.semantic,
123
+ },
109
124
  sourceCacheStatus: {
110
125
  name: "rfc_source_cache_status",
111
126
  title: "Inspect an RFC source cache entry",
package/src/main.ts CHANGED
@@ -17,12 +17,14 @@ import {
17
17
  executeResearch,
18
18
  executeSourceCacheRemove,
19
19
  executeSourceCacheStatus,
20
+ executeSourceText,
20
21
  renderAuthStatus,
21
22
  renderCitationVerification,
22
23
  renderResearchResult,
23
24
  renderEstimatedUsd,
24
25
  renderSourceCacheRemove,
25
26
  renderSourceCacheStatus,
27
+ renderSourceText,
26
28
  toRfcOperationErrorEnvelope,
27
29
  type RfcOperationOptions,
28
30
  type RfcOperationWarning,
@@ -181,6 +183,19 @@ const offset = Flag.String("offset").pipe(
181
183
  Flag.optional,
182
184
  );
183
185
 
186
+ const startOffset = Flag.String("start-offset").pipe(
187
+ Flag.withDescription("Inclusive UTF-8 byte start of an exact RFC source range"),
188
+ Flag.optional,
189
+ );
190
+ const endOffset = Flag.String("end-offset").pipe(
191
+ Flag.withDescription("Exclusive UTF-8 byte end of an exact RFC source range"),
192
+ Flag.optional,
193
+ );
194
+ const expectedSourceHash = Flag.String("expected-source-hash").pipe(
195
+ Flag.withDescription("Reject a source changed since a previous metadata or range read"),
196
+ Flag.optional,
197
+ );
198
+
184
199
  const credentialFromStdin = Flag.Boolean("stdin").pipe(
185
200
  Flag.withDescription("Read the TypeSafe API key from standard input; never use an argv value"),
186
201
  Flag.withDefault(false),
@@ -446,6 +461,67 @@ const makeApplication = (dependencies: RfcCliDependencies) => {
446
461
  Option.getOrUndefined(selectedRfcSearchApiKey) ?? nonEmptyEnv("RFC_SEARCH_API_KEY"),
447
462
  });
448
463
 
464
+ const sourceTextCommand = Command.make(
465
+ "source-text",
466
+ {
467
+ cacheDirectory,
468
+ datatrackerApiUrl,
469
+ format,
470
+ rfc: cacheRfc,
471
+ rfcArgument,
472
+ startOffset,
473
+ endOffset,
474
+ expectedSourceHash,
475
+ },
476
+ Effect.fn(function* (flags) {
477
+ const rfc = resolveRequiredArgumentInput("--rfc", flags.rfc, flags.rfcArgument);
478
+ const parseByteOffset = (value: Option.Option<string>): number | undefined => {
479
+ const raw = Option.getOrUndefined(value);
480
+ if (raw === undefined) return undefined;
481
+ const parsed = Number(raw);
482
+ if (!/^(0|[1-9]\d*)$/.test(raw) || !Number.isSafeInteger(parsed)) {
483
+ throw new InvalidInputError({
484
+ reason: "Source offsets must be non-negative safe integers",
485
+ });
486
+ }
487
+ return parsed;
488
+ };
489
+ const request = {
490
+ schemaVersion,
491
+ rfc,
492
+ ...(Option.isSome(flags.startOffset)
493
+ ? { startOffset: parseByteOffset(flags.startOffset) }
494
+ : {}),
495
+ ...(Option.isSome(flags.endOffset) ? { endOffset: parseByteOffset(flags.endOffset) } : {}),
496
+ ...(Option.isSome(flags.expectedSourceHash)
497
+ ? { expectedSourceHash: flags.expectedSourceHash.value }
498
+ : {}),
499
+ };
500
+ const result = yield* Effect.tryPromise({
501
+ try: () =>
502
+ executeSourceText(
503
+ request,
504
+ operationOptions(flags.cacheDirectory, flags.datatrackerApiUrl, Option.none()),
505
+ dependencies,
506
+ ),
507
+ catch: (error) => error,
508
+ });
509
+ if (resolveOutputFormat(flags.format) === "json") {
510
+ yield* writeStdout(JSON.stringify(result));
511
+ } else if (result.text === null) {
512
+ yield* writeStdout(renderSourceText(result));
513
+ } else {
514
+ // An exact range is emitted without an added newline.
515
+ const text = result.text;
516
+ yield* Effect.sync(() => dependencies.writeStdout(text));
517
+ }
518
+ }),
519
+ ).pipe(
520
+ Command.withDescription(
521
+ "Read RFC source metadata or exact UTF-8 byte ranges only when full text is explicitly required; prefer research and citation tools for questions",
522
+ ),
523
+ );
524
+
449
525
  const sourceCacheStatusCommand = Command.make(
450
526
  "status",
451
527
  {
@@ -780,6 +856,7 @@ const makeApplication = (dependencies: RfcCliDependencies) => {
780
856
  Command.withSubcommands([
781
857
  authCommand,
782
858
  sourceCacheCommand,
859
+ sourceTextCommand,
783
860
  costsCommand,
784
861
  researchCommand,
785
862
  verifyCitationCommand,
package/src/mcp.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  InvalidInputError,
5
5
  RfcSourceCacheRemoveResultSchema,
6
6
  RfcSourceCacheStatusSchema,
7
+ RfcSourceTextResultSchema,
7
8
  datatrackerTopicSearchTermLimit,
8
9
  datatrackerTopicSearchTermMaximumCharacters,
9
10
  retrievalPolicy,
@@ -27,11 +28,13 @@ import {
27
28
  executeResearch,
28
29
  executeSourceCacheRemove,
29
30
  executeSourceCacheStatus,
31
+ executeSourceText,
30
32
  renderAuthStatus,
31
33
  renderCitationVerification,
32
34
  renderResearchResult,
33
35
  renderSourceCacheRemove,
34
36
  renderSourceCacheStatus,
37
+ renderSourceText,
35
38
  toRfcOperationErrorEnvelope,
36
39
  type RfcOperationDependencies,
37
40
  type RfcOperationOptions,
@@ -83,6 +86,10 @@ Verify one factual claim against one exact RFC quotation. Inputs are \`rfc\`, \`
83
86
  - \`contradicted\`: the quotation conflicts with the claim.
84
87
  - \`fabricated\`: the supplied quotation is absent from the authoritative source.
85
88
 
89
+ ### rfc_source_text
90
+
91
+ Read an authoritative RFC Editor plain-text source only when the full RFC text is explicitly required or requested; for ordinary questions prefer \`rfc_research\` and \`rfc_verify_citation\`. An identifier-only request returns a parsed heading index with half-open UTF-8 byte ranges, source hash, and total bytes but no text. Supply both \`startOffset\` (inclusive) and \`endOffset\` (exclusive) to retrieve exactly that byte slice, without truncation. Ranges from citations use the same offsets. On later pages supply \`expectedSourceHash\`; if revalidation changes the source, the request fails rather than mixing snapshots. Large ranges produce correspondingly large results.
92
+
86
93
  ### rfc_source_cache_status
87
94
 
88
95
  Inspect one named RFC source-cache entry without network access.
@@ -149,6 +156,17 @@ const CitationInputSchema = Schema.Struct({
149
156
  ),
150
157
  });
151
158
 
159
+ const SourceTextInputSchema = Schema.Struct({
160
+ rfc: describedString(descriptions.sourceRfc),
161
+ startOffset: Schema.optionalKey(
162
+ Schema.Natural.pipe(Schema.annotate({ description: descriptions.sourceStart })),
163
+ ),
164
+ endOffset: Schema.optionalKey(
165
+ Schema.Natural.pipe(Schema.annotate({ description: descriptions.sourceEnd })),
166
+ ),
167
+ expectedSourceHash: Schema.optionalKey(describedString(descriptions.expectedSourceHash)),
168
+ });
169
+
152
170
  const RfcInputSchema = Schema.Struct({
153
171
  rfc: describedString(descriptions.cacheRfc),
154
172
  });
@@ -295,6 +313,37 @@ export const createRfcMcpServer = (
295
313
  },
296
314
  );
297
315
 
316
+ server.registerTool(
317
+ rfcAgentToolMetadata.sourceText.name,
318
+ {
319
+ title: rfcAgentToolMetadata.sourceText.title,
320
+ description: rfcAgentToolMetadata.sourceText.description,
321
+ inputSchema: toMcpSchema(SourceTextInputSchema),
322
+ outputSchema: toMcpSchema(RfcSourceTextResultSchema),
323
+ annotations: rfcAgentToolMetadata.sourceText.annotations,
324
+ },
325
+ async ({ rfc, startOffset, endOffset, expectedSourceHash }) => {
326
+ try {
327
+ return plainSuccess(
328
+ await executeSourceText(
329
+ {
330
+ schemaVersion,
331
+ rfc,
332
+ ...(startOffset === undefined ? {} : { startOffset }),
333
+ ...(endOffset === undefined ? {} : { endOffset }),
334
+ ...(expectedSourceHash === undefined ? {} : { expectedSourceHash }),
335
+ },
336
+ options,
337
+ dependencies,
338
+ ),
339
+ renderSourceText,
340
+ );
341
+ } catch (error) {
342
+ return toolError(error);
343
+ }
344
+ },
345
+ );
346
+
298
347
  server.registerTool(
299
348
  rfcAgentToolMetadata.sourceCacheStatus.name,
300
349
  {
package/src/operations.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import {
2
2
  ConfigurationError,
3
+ InvalidInputError,
3
4
  createRfcClient,
4
5
  decodeCitationVerificationRequest,
5
6
  decodeResearchRequest,
6
7
  schemaVersion,
8
+ RfcSourceTextRequestSchema,
7
9
  toErrorEnvelope,
8
10
  type CitationVerificationRequest,
9
11
  type CitationVerificationResult,
@@ -13,7 +15,10 @@ import {
13
15
  type RfcClient,
14
16
  type RfcSourceCacheRemoveResult,
15
17
  type RfcSourceCacheStatus,
18
+ type RfcSourceTextRequest,
19
+ type RfcSourceTextResult,
16
20
  } from "@wyattjoh/rfc-core";
21
+ import { Schema } from "effect";
17
22
  import { readCliConfig } from "./config";
18
23
  import {
19
24
  CredentialInputError,
@@ -34,6 +39,7 @@ export {
34
39
  renderResearchResult,
35
40
  renderSourceCacheRemove,
36
41
  renderSourceCacheStatus,
42
+ renderSourceText,
37
43
  researchResultAgentJson,
38
44
  } from "./renderers";
39
45
 
@@ -293,6 +299,41 @@ export const executeCitationVerification = async (
293
299
  };
294
300
  };
295
301
 
302
+ /**
303
+ * Fetch exact canonical RFC text or a metadata-only section index.
304
+ *
305
+ * @param request Versioned RFC identifier and optional UTF-8 byte range.
306
+ * @param options Trusted process configuration.
307
+ * @param dependencies Injectable operation boundaries.
308
+ * @returns Source identity and either headings or the requested text.
309
+ */
310
+ export const executeSourceText = (
311
+ request: RfcSourceTextRequest | unknown,
312
+ options: RfcOperationOptions,
313
+ dependencies: RfcOperationDependencies,
314
+ ): Promise<RfcSourceTextResult> => {
315
+ let decoded: RfcSourceTextRequest;
316
+ try {
317
+ decoded = Schema.decodeUnknownSync(RfcSourceTextRequestSchema)(request);
318
+ } catch {
319
+ throw new InvalidInputError({
320
+ reason:
321
+ "Source text input must use schema version 3 with a named RFC and optional byte range",
322
+ });
323
+ }
324
+ return withClient(
325
+ () =>
326
+ dependencies.createClient({
327
+ cacheDirectory: options.cacheDirectory,
328
+ datatrackerApiUrl: options.datatrackerApiUrl,
329
+ modelAlias: undefined,
330
+ typeSafeApiKey: undefined,
331
+ typeSafeApiUrl: undefined,
332
+ }),
333
+ (client) => client.sourceText(decoded),
334
+ );
335
+ };
336
+
296
337
  /**
297
338
  * Inspect one named RFC source-cache entry without network access.
298
339
  *
package/src/renderers.ts CHANGED
@@ -6,6 +6,7 @@ import type {
6
6
  ResearchResult,
7
7
  RfcSourceCacheRemoveResult,
8
8
  RfcSourceCacheStatus,
9
+ RfcSourceTextResult,
9
10
  } from "@wyattjoh/rfc-core";
10
11
  import type { AuthStatus } from "./credentials";
11
12
 
@@ -228,6 +229,25 @@ export const renderSourceCacheStatus = (result: RfcSourceCacheStatus): string =>
228
229
  export const renderSourceCacheRemove = (result: RfcSourceCacheRemoveResult): string =>
229
230
  `RFC: ${result.rfc}\nCache: ${result.removed ? "removed" : "missing"}`;
230
231
 
232
+ /**
233
+ * Render source navigation metadata or the exact requested source text.
234
+ *
235
+ * @param result Source text result from the canonical RFC source.
236
+ * @returns Readable metadata or the unaltered text slice.
237
+ */
238
+ export const renderSourceText = (result: RfcSourceTextResult): string =>
239
+ result.text === null
240
+ ? [
241
+ `RFC: ${result.rfc}`,
242
+ `Source: ${result.sourceUrl}`,
243
+ `Hash: ${result.sourceHash}`,
244
+ `Bytes: ${result.totalBytes}`,
245
+ ...result.headings.map((heading) =>
246
+ `${heading.number ?? ""} ${heading.title} [${heading.startOffset}-${heading.endOffset}]`.trim(),
247
+ ),
248
+ ].join("\n")
249
+ : result.text;
250
+
231
251
  /**
232
252
  * Render safe credential status metadata.
233
253
  *