@atrib/summarize 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 +190 -0
- package/README.md +78 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.js +159 -0
- package/dist/llm.d.ts +29 -0
- package/dist/llm.js +61 -0
- package/dist/main.d.ts +2 -0
- package/dist/main.js +16 -0
- package/dist/prompt.d.ts +16 -0
- package/dist/prompt.js +95 -0
- package/dist/storage.d.ts +36 -0
- package/dist/storage.js +84 -0
- package/package.json +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and Derivative Works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of discussing and
|
|
55
|
+
improving the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or otherwise designated in writing by the copyright owner as
|
|
57
|
+
"Not a Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and subsequently
|
|
61
|
+
incorporated within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or a Contribution
|
|
81
|
+
incorporated within the Work constitutes direct or contributory patent
|
|
82
|
+
infringement, then any patent licenses granted to You under this License
|
|
83
|
+
for that Work shall terminate as of the date such litigation is filed.
|
|
84
|
+
|
|
85
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
86
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
87
|
+
modifications, and in Source or Object form, provided that You
|
|
88
|
+
meet the following conditions:
|
|
89
|
+
|
|
90
|
+
(a) You must give any other recipients of the Work or Derivative Works
|
|
91
|
+
a copy of this License; and
|
|
92
|
+
|
|
93
|
+
(b) You must cause any modified files to carry prominent notices
|
|
94
|
+
stating that You changed the files; and
|
|
95
|
+
|
|
96
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
97
|
+
that You distribute, all copyright, patent, trademark, and
|
|
98
|
+
attribution notices from the Source form of the Work,
|
|
99
|
+
excluding those notices that do not pertain to any part of
|
|
100
|
+
the Derivative Works; and
|
|
101
|
+
|
|
102
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
103
|
+
distribution, You must include a readable copy of the attribution
|
|
104
|
+
notices contained within such NOTICE file, in at least one
|
|
105
|
+
of the following places: within a NOTICE text file distributed
|
|
106
|
+
as part of the Derivative Works; within the Source form or
|
|
107
|
+
documentation, if provided along with the Derivative Works; or,
|
|
108
|
+
within a display generated by the Derivative Works, if and
|
|
109
|
+
wherever such third-party notices normally appear. The contents
|
|
110
|
+
of the NOTICE file are for informational purposes only and
|
|
111
|
+
do not modify the License. You may add Your own attribution
|
|
112
|
+
notices within Derivative Works that You distribute, alongside
|
|
113
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
114
|
+
that such additional attribution notices cannot be construed
|
|
115
|
+
as modifying the License.
|
|
116
|
+
|
|
117
|
+
You may add Your own license statement for Your modifications and
|
|
118
|
+
may provide additional grant of rights to use, modify, or distribute
|
|
119
|
+
those modifications in accordance with this License.
|
|
120
|
+
|
|
121
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
122
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
123
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
124
|
+
this License, without any additional terms or conditions.
|
|
125
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
126
|
+
the terms of any separate license agreement you may have executed
|
|
127
|
+
with Licensor regarding such Contributions.
|
|
128
|
+
|
|
129
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
130
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
131
|
+
except as required for reasonable and customary use in describing the
|
|
132
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
133
|
+
|
|
134
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
135
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
136
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
137
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
138
|
+
implied, including, without limitation, any warranties or conditions
|
|
139
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
140
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
141
|
+
appropriateness of using or reproducing the Work and assume any
|
|
142
|
+
risks associated with Your exercise of permissions under this License.
|
|
143
|
+
|
|
144
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
145
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
146
|
+
unless required by applicable law (such as deliberate and grossly
|
|
147
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
148
|
+
liable to You for damages, including any direct, indirect, special,
|
|
149
|
+
incidental, or exemplary damages of any character arising as a
|
|
150
|
+
result of this License or out of the use or inability to use the
|
|
151
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
152
|
+
work stoppage, computer failure or malfunction, or all other
|
|
153
|
+
commercial damages or losses), even if such Contributor has been
|
|
154
|
+
advised of the possibility of such damages.
|
|
155
|
+
|
|
156
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
157
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
158
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
159
|
+
or other liability obligations and/or rights consistent with this
|
|
160
|
+
License. However, in accepting such obligations, You may act only
|
|
161
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
162
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
163
|
+
defend, and hold each Contributor harmless for any liability
|
|
164
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
165
|
+
of your accepting any such warranty or additional liability.
|
|
166
|
+
|
|
167
|
+
END OF TERMS AND CONDITIONS
|
|
168
|
+
|
|
169
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
170
|
+
|
|
171
|
+
To apply the Apache License to your work, attach the following
|
|
172
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
173
|
+
replaced with your own identifying information. (Don't include
|
|
174
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
175
|
+
comment syntax for the file format in question. Also, an optional
|
|
176
|
+
"Statement of Purpose" appears after the copyright notice.
|
|
177
|
+
|
|
178
|
+
Copyright 2025-2026 Atrib contributors
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
189
|
+
implied. See the License for the specific language governing
|
|
190
|
+
permissions and limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# @atrib/atrib-summarize
|
|
2
|
+
|
|
3
|
+
MCP server exposing the `summarize` tool — synthesizes a narrative across N records using an OpenAI-compatible LLM.
|
|
4
|
+
|
|
5
|
+
Closes the consumer-side cognitive-loop primitive companion to `atrib-trace`: trace returns the causal chain (structural); summarize returns the synthesized meaning across the chain (semantic). Both read the same local mirror including the optional `_local` sidecar.
|
|
6
|
+
|
|
7
|
+
## Tool
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
mcp__atrib-summarize__summarize({
|
|
11
|
+
context_id?: string, // 32-hex trace; summarize all records in it
|
|
12
|
+
record_hashes?: string[], // explicit list; unioned with context_id
|
|
13
|
+
focus?: string, // optional steering for the synthesis
|
|
14
|
+
max_records?: number, // cap on records fed to LLM (default 50, max 200)
|
|
15
|
+
model?: string // override model from env
|
|
16
|
+
})
|
|
17
|
+
→ {
|
|
18
|
+
narrative: string | null,
|
|
19
|
+
cited_record_hashes: string[],
|
|
20
|
+
records_summarized: number,
|
|
21
|
+
records_skipped: number, // beyond max_records
|
|
22
|
+
records_with_sidecar: number, // had semantic content
|
|
23
|
+
records_without_sidecar: number, // legacy bare records, impoverished input
|
|
24
|
+
model_used: string | null,
|
|
25
|
+
warnings: string[]
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## LLM provider
|
|
30
|
+
|
|
31
|
+
OpenAI-compatible HTTP. Defaults to NVIDIA NIM with `qwen/qwen3.5-397b-a17b`. Override via env or per-call `model` input:
|
|
32
|
+
|
|
33
|
+
| Env var | Default |
|
|
34
|
+
|---|---|
|
|
35
|
+
| `ATRIB_SUMMARIZE_API_KEY` | (fallback to `NVIDIA_API_KEY` then `NVIDIA_NIM_API_KEY`) |
|
|
36
|
+
| `ATRIB_SUMMARIZE_BASE_URL` | `https://integrate.api.nvidia.com/v1` |
|
|
37
|
+
| `ATRIB_SUMMARIZE_MODEL` | `qwen/qwen3.5-397b-a17b` |
|
|
38
|
+
| `ATRIB_SUMMARIZE_MAX_TOKENS` | `4000` |
|
|
39
|
+
| `ATRIB_SUMMARIZE_TEMPERATURE` | `0.3` |
|
|
40
|
+
| `ATRIB_SUMMARIZE_TIMEOUT_MS` | `120000` |
|
|
41
|
+
|
|
42
|
+
Without an API key, the tool returns a warnings-only response per the §5.8 graceful-degradation contract.
|
|
43
|
+
|
|
44
|
+
## Reads
|
|
45
|
+
|
|
46
|
+
Same as `@atrib/atrib-trace`: every `*.jsonl` mirror under `~/.atrib/records/` (override via `ATRIB_RECORDS_DIR`). Tolerates both legacy bare-record and current envelope shapes.
|
|
47
|
+
|
|
48
|
+
When a record lacks a `_local` sidecar (legacy entry), the prompt includes a marker telling the LLM the input is impoverished — only event_type + cryptographic metadata is available — so the synthesis can be honest about gaps. The output reports `records_with_sidecar` and `records_without_sidecar` counts so callers know how rich the input was.
|
|
49
|
+
|
|
50
|
+
## Behaviors
|
|
51
|
+
|
|
52
|
+
- **Selection**: `record_hashes` ∪ records-with-matching-`context_id`, deduplicated.
|
|
53
|
+
- **Capping**: chronological-ascending sort, then take `max_records`. Skipped count surfaced.
|
|
54
|
+
- **Honest input flagging**: a per-record line in the prompt marks records lacking semantic content; the system prompt instructs the LLM not to invent semantics.
|
|
55
|
+
- **Network access only on LLM call**: storage reads are local. Tests use the same FORBIDDEN_HOSTS guard as the rest of the workspace to prevent fixture leakage.
|
|
56
|
+
- **No retry on LLM failure**: surfaces the error in `warnings` and returns null narrative. Caller decides whether to retry with smaller `max_records` or different model.
|
|
57
|
+
|
|
58
|
+
## Wire-up
|
|
59
|
+
|
|
60
|
+
Add to your MCP host config:
|
|
61
|
+
|
|
62
|
+
```json
|
|
63
|
+
{
|
|
64
|
+
"atrib-summarize": {
|
|
65
|
+
"command": "node",
|
|
66
|
+
"args": ["/path/to/atrib-summarize/dist/main.js"],
|
|
67
|
+
"env": {
|
|
68
|
+
"NVIDIA_API_KEY": "..."
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Status
|
|
75
|
+
|
|
76
|
+
Initial scaffold (v0.1.0). 6 unit tests covering record selection (by hash, by context, unioned, missing-skip) + degradation paths (no inputs, no API key). Integration test against a real LLM is gated behind `ATRIB_SUMMARIZE_API_KEY` and not run in CI.
|
|
77
|
+
|
|
78
|
+
The companion `atrib-trace` is the structural primitive; together they close the consumer side of the cognitive loop.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* atrib-summarize MCP server: registers the `summarize` tool that reads
|
|
3
|
+
* a set of records (by context_id, by record_hashes, or both) and asks
|
|
4
|
+
* an OpenAI-compatible LLM to synthesize a narrative across them.
|
|
5
|
+
*
|
|
6
|
+
* Closes the consumer-side cognitive-loop primitive companion to trace:
|
|
7
|
+
* trace returns the causal chain (structural); summarize returns the
|
|
8
|
+
* synthesized meaning across that chain (semantic). Both read the same
|
|
9
|
+
* local mirror including the optional _local sidecar.
|
|
10
|
+
*
|
|
11
|
+
* LLM access via OpenAI-compatible HTTP. Defaults to NVIDIA NIM with the
|
|
12
|
+
* Qwen 397B model; override via env vars or per-call model override.
|
|
13
|
+
* Without an API key, the tool returns a warnings-only response per the
|
|
14
|
+
* §5.8 graceful-degradation pattern.
|
|
15
|
+
*/
|
|
16
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
17
|
+
import { z } from 'zod';
|
|
18
|
+
import { type IndexedRecord } from './storage.js';
|
|
19
|
+
declare const SummarizeInput: z.ZodObject<{
|
|
20
|
+
context_id: z.ZodOptional<z.ZodString>;
|
|
21
|
+
record_hashes: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
|
|
22
|
+
focus: z.ZodOptional<z.ZodString>;
|
|
23
|
+
max_records: z.ZodOptional<z.ZodNumber>;
|
|
24
|
+
model: z.ZodOptional<z.ZodString>;
|
|
25
|
+
}, "strip", z.ZodTypeAny, {
|
|
26
|
+
context_id?: string | undefined;
|
|
27
|
+
model?: string | undefined;
|
|
28
|
+
record_hashes?: string[] | undefined;
|
|
29
|
+
focus?: string | undefined;
|
|
30
|
+
max_records?: number | undefined;
|
|
31
|
+
}, {
|
|
32
|
+
context_id?: string | undefined;
|
|
33
|
+
model?: string | undefined;
|
|
34
|
+
record_hashes?: string[] | undefined;
|
|
35
|
+
focus?: string | undefined;
|
|
36
|
+
max_records?: number | undefined;
|
|
37
|
+
}>;
|
|
38
|
+
interface SummarizeOutput {
|
|
39
|
+
narrative: string | null;
|
|
40
|
+
cited_record_hashes: string[];
|
|
41
|
+
records_summarized: number;
|
|
42
|
+
records_skipped: number;
|
|
43
|
+
records_with_sidecar: number;
|
|
44
|
+
records_without_sidecar: number;
|
|
45
|
+
model_used: string | null;
|
|
46
|
+
warnings: string[];
|
|
47
|
+
}
|
|
48
|
+
export interface AtribSummarizeServer {
|
|
49
|
+
mcp: McpServer;
|
|
50
|
+
}
|
|
51
|
+
export declare function createAtribSummarizeServer(): Promise<AtribSummarizeServer>;
|
|
52
|
+
declare function handleSummarize(input: z.infer<typeof SummarizeInput>): Promise<SummarizeOutput>;
|
|
53
|
+
declare function selectRecords(input: z.infer<typeof SummarizeInput>, byHash: Map<string, IndexedRecord>, newestFirst: IndexedRecord[]): IndexedRecord[];
|
|
54
|
+
export declare const __test_only__: {
|
|
55
|
+
handleSummarize: typeof handleSummarize;
|
|
56
|
+
selectRecords: typeof selectRecords;
|
|
57
|
+
};
|
|
58
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* atrib-summarize MCP server: registers the `summarize` tool that reads
|
|
4
|
+
* a set of records (by context_id, by record_hashes, or both) and asks
|
|
5
|
+
* an OpenAI-compatible LLM to synthesize a narrative across them.
|
|
6
|
+
*
|
|
7
|
+
* Closes the consumer-side cognitive-loop primitive companion to trace:
|
|
8
|
+
* trace returns the causal chain (structural); summarize returns the
|
|
9
|
+
* synthesized meaning across that chain (semantic). Both read the same
|
|
10
|
+
* local mirror including the optional _local sidecar.
|
|
11
|
+
*
|
|
12
|
+
* LLM access via OpenAI-compatible HTTP. Defaults to NVIDIA NIM with the
|
|
13
|
+
* Qwen 397B model; override via env vars or per-call model override.
|
|
14
|
+
* Without an API key, the tool returns a warnings-only response per the
|
|
15
|
+
* §5.8 graceful-degradation pattern.
|
|
16
|
+
*/
|
|
17
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { loadAllRecords } from './storage.js';
|
|
20
|
+
import { callLlm, resolveLlmConfig } from './llm.js';
|
|
21
|
+
import { buildSystemPrompt, buildUserMessage } from './prompt.js';
|
|
22
|
+
const SHA256_REF_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
|
23
|
+
const HEX_32_PATTERN = /^[0-9a-f]{32}$/;
|
|
24
|
+
const SummarizeInput = z.object({
|
|
25
|
+
context_id: z.string().regex(HEX_32_PATTERN).optional().describe("When supplied, summarize every record sharing this 32-hex trace identifier. " +
|
|
26
|
+
"Mutually composable with record_hashes: if both, the union of records is used."),
|
|
27
|
+
record_hashes: z.array(z.string().regex(SHA256_REF_PATTERN)).optional().describe("Explicit list of 'sha256:<64-hex>' record hashes to summarize. Records not " +
|
|
28
|
+
"in the local mirror are silently skipped (use trace to inspect dangling)."),
|
|
29
|
+
focus: z.string().min(1).max(2000).optional().describe('Optional steering for the synthesis (e.g. "what decisions did I make", ' +
|
|
30
|
+
'"why did I revise X", "what are the load-bearing claims"). Defaults to a ' +
|
|
31
|
+
'general "summarize what the agent did and why" focus.'),
|
|
32
|
+
max_records: z.number().int().min(1).max(200).optional().describe('Cap on records fed to the LLM, default 50. Records beyond the cap (after ' +
|
|
33
|
+
'sorting by timestamp ascending) are skipped and counted in records_skipped. ' +
|
|
34
|
+
'Increase carefully — large prompts run slower + cost more + risk model ' +
|
|
35
|
+
'context limits.'),
|
|
36
|
+
model: z.string().min(1).max(200).optional().describe('Override the configured model for this call. Format depends on provider ' +
|
|
37
|
+
'(NVIDIA NIM uses e.g. "qwen/qwen3.5-397b-a17b"). Defaults to env ' +
|
|
38
|
+
'ATRIB_SUMMARIZE_MODEL or the package default.'),
|
|
39
|
+
});
|
|
40
|
+
export async function createAtribSummarizeServer() {
|
|
41
|
+
const mcp = new McpServer({ name: 'atrib-summarize', version: '0.1.0' });
|
|
42
|
+
mcp.registerTool('summarize', {
|
|
43
|
+
title: 'synthesize narrative across signed records',
|
|
44
|
+
description: 'Read a set of records (by context_id and/or record_hashes) and ask ' +
|
|
45
|
+
'an LLM to synthesize a coherent narrative across them. Reads the local ' +
|
|
46
|
+
'signed-record mirror (~/.atrib/records/*.jsonl) including the optional ' +
|
|
47
|
+
'_local sidecar for semantic content. Records without a sidecar are ' +
|
|
48
|
+
'flagged so the LLM can be honest about impoverished input.',
|
|
49
|
+
inputSchema: SummarizeInput.shape,
|
|
50
|
+
}, async (rawInput) => {
|
|
51
|
+
const input = SummarizeInput.parse(rawInput);
|
|
52
|
+
const result = await handleSummarize(input);
|
|
53
|
+
return {
|
|
54
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
55
|
+
};
|
|
56
|
+
});
|
|
57
|
+
return { mcp };
|
|
58
|
+
}
|
|
59
|
+
async function handleSummarize(input) {
|
|
60
|
+
const warnings = [];
|
|
61
|
+
const maxRecords = input.max_records ?? 50;
|
|
62
|
+
if (!input.context_id && !input.record_hashes) {
|
|
63
|
+
warnings.push('one of context_id or record_hashes is required');
|
|
64
|
+
return emptyOutput(warnings);
|
|
65
|
+
}
|
|
66
|
+
const llmCfg = resolveLlmConfig(input.model);
|
|
67
|
+
if (!llmCfg) {
|
|
68
|
+
warnings.push('no LLM API key resolved (set ATRIB_SUMMARIZE_API_KEY or NVIDIA_API_KEY); cannot synthesize');
|
|
69
|
+
return emptyOutput(warnings);
|
|
70
|
+
}
|
|
71
|
+
// Load local mirror once; filter to the requested set.
|
|
72
|
+
const { byHash, newestFirst } = loadAllRecords();
|
|
73
|
+
const selected = selectRecords(input, byHash, newestFirst);
|
|
74
|
+
if (selected.length === 0) {
|
|
75
|
+
warnings.push('no records matched the request');
|
|
76
|
+
return { ...emptyOutput(warnings), model_used: llmCfg.model };
|
|
77
|
+
}
|
|
78
|
+
// Sort ascending by timestamp + apply max_records cap.
|
|
79
|
+
selected.sort((a, b) => a.record.timestamp - b.record.timestamp);
|
|
80
|
+
const summarized = selected.slice(0, maxRecords);
|
|
81
|
+
const skipped = selected.length - summarized.length;
|
|
82
|
+
if (skipped > 0) {
|
|
83
|
+
warnings.push(`${skipped} record${skipped === 1 ? '' : 's'} skipped beyond max_records=${maxRecords}`);
|
|
84
|
+
}
|
|
85
|
+
const withSidecar = summarized.filter((r) => r.local).length;
|
|
86
|
+
const withoutSidecar = summarized.length - withSidecar;
|
|
87
|
+
if (withoutSidecar > 0) {
|
|
88
|
+
warnings.push(`${withoutSidecar} record${withoutSidecar === 1 ? '' : 's'} lacked a _local sidecar; LLM was given only event_type + cryptographic metadata for those`);
|
|
89
|
+
}
|
|
90
|
+
const systemMsg = buildSystemPrompt();
|
|
91
|
+
const userMsg = buildUserMessage(summarized, input.focus);
|
|
92
|
+
let narrative = '';
|
|
93
|
+
let modelUsed = llmCfg.model;
|
|
94
|
+
try {
|
|
95
|
+
const llmResult = await callLlm(llmCfg, systemMsg, userMsg);
|
|
96
|
+
narrative = llmResult.content;
|
|
97
|
+
modelUsed = llmResult.model;
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
warnings.push(`LLM call failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
101
|
+
return {
|
|
102
|
+
narrative: null,
|
|
103
|
+
cited_record_hashes: summarized.map((r) => r.record_hash),
|
|
104
|
+
records_summarized: summarized.length,
|
|
105
|
+
records_skipped: skipped,
|
|
106
|
+
records_with_sidecar: withSidecar,
|
|
107
|
+
records_without_sidecar: withoutSidecar,
|
|
108
|
+
model_used: llmCfg.model,
|
|
109
|
+
warnings,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
narrative,
|
|
114
|
+
cited_record_hashes: summarized.map((r) => r.record_hash),
|
|
115
|
+
records_summarized: summarized.length,
|
|
116
|
+
records_skipped: skipped,
|
|
117
|
+
records_with_sidecar: withSidecar,
|
|
118
|
+
records_without_sidecar: withoutSidecar,
|
|
119
|
+
model_used: modelUsed,
|
|
120
|
+
warnings,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function selectRecords(input, byHash, newestFirst) {
|
|
124
|
+
const seen = new Set();
|
|
125
|
+
const out = [];
|
|
126
|
+
if (input.record_hashes) {
|
|
127
|
+
for (const h of input.record_hashes) {
|
|
128
|
+
const idx = byHash.get(h);
|
|
129
|
+
if (idx && !seen.has(idx.record_hash)) {
|
|
130
|
+
seen.add(idx.record_hash);
|
|
131
|
+
out.push(idx);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (input.context_id) {
|
|
136
|
+
for (const r of newestFirst) {
|
|
137
|
+
if (r.record.context_id === input.context_id && !seen.has(r.record_hash)) {
|
|
138
|
+
seen.add(r.record_hash);
|
|
139
|
+
out.push(r);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return out;
|
|
144
|
+
}
|
|
145
|
+
function emptyOutput(warnings) {
|
|
146
|
+
return {
|
|
147
|
+
narrative: null,
|
|
148
|
+
cited_record_hashes: [],
|
|
149
|
+
records_summarized: 0,
|
|
150
|
+
records_skipped: 0,
|
|
151
|
+
records_with_sidecar: 0,
|
|
152
|
+
records_without_sidecar: 0,
|
|
153
|
+
model_used: null,
|
|
154
|
+
warnings,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
// Test-only export — lets unit tests exercise the assembly logic without
|
|
158
|
+
// going through the McpServer transport.
|
|
159
|
+
export const __test_only__ = { handleSummarize, selectRecords };
|
package/dist/llm.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible chat completion client.
|
|
3
|
+
*
|
|
4
|
+
* Defaults to the env-configured endpoint and model. Designed for use
|
|
5
|
+
* with NVIDIA NIM, Together, OpenRouter, or any OpenAI-compatible
|
|
6
|
+
* provider. The summarize tool is the only consumer.
|
|
7
|
+
*/
|
|
8
|
+
export interface LlmConfig {
|
|
9
|
+
baseUrl: string;
|
|
10
|
+
model: string;
|
|
11
|
+
apiKey: string;
|
|
12
|
+
maxTokens: number;
|
|
13
|
+
temperature: number;
|
|
14
|
+
timeoutMs: number;
|
|
15
|
+
}
|
|
16
|
+
export interface LlmResult {
|
|
17
|
+
content: string;
|
|
18
|
+
model: string;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Resolve LLM config from env with documented defaults. Caller-supplied
|
|
22
|
+
* model override (from the MCP tool input) wins over env.
|
|
23
|
+
*/
|
|
24
|
+
export declare function resolveLlmConfig(modelOverride?: string): LlmConfig | null;
|
|
25
|
+
/**
|
|
26
|
+
* POST one chat completion. Throws on HTTP error so the caller can
|
|
27
|
+
* surface it via warnings; never silently returns empty content.
|
|
28
|
+
*/
|
|
29
|
+
export declare function callLlm(cfg: LlmConfig, systemMsg: string, userMsg: string): Promise<LlmResult>;
|
package/dist/llm.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Resolve LLM config from env with documented defaults. Caller-supplied
|
|
4
|
+
* model override (from the MCP tool input) wins over env.
|
|
5
|
+
*/
|
|
6
|
+
export function resolveLlmConfig(modelOverride) {
|
|
7
|
+
const apiKey = process.env['ATRIB_SUMMARIZE_API_KEY'] ??
|
|
8
|
+
process.env['NVIDIA_API_KEY'] ??
|
|
9
|
+
process.env['NVIDIA_NIM_API_KEY'] ??
|
|
10
|
+
'';
|
|
11
|
+
if (!apiKey)
|
|
12
|
+
return null;
|
|
13
|
+
return {
|
|
14
|
+
baseUrl: process.env['ATRIB_SUMMARIZE_BASE_URL'] ?? 'https://integrate.api.nvidia.com/v1',
|
|
15
|
+
model: modelOverride ?? process.env['ATRIB_SUMMARIZE_MODEL'] ?? 'qwen/qwen3.5-397b-a17b',
|
|
16
|
+
apiKey,
|
|
17
|
+
maxTokens: Number(process.env['ATRIB_SUMMARIZE_MAX_TOKENS'] ?? 4000),
|
|
18
|
+
temperature: Number(process.env['ATRIB_SUMMARIZE_TEMPERATURE'] ?? 0.3),
|
|
19
|
+
timeoutMs: Number(process.env['ATRIB_SUMMARIZE_TIMEOUT_MS'] ?? 120000),
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* POST one chat completion. Throws on HTTP error so the caller can
|
|
24
|
+
* surface it via warnings; never silently returns empty content.
|
|
25
|
+
*/
|
|
26
|
+
export async function callLlm(cfg, systemMsg, userMsg) {
|
|
27
|
+
const url = cfg.baseUrl.replace(/\/$/, '') + '/chat/completions';
|
|
28
|
+
const ctrl = new AbortController();
|
|
29
|
+
const timer = setTimeout(() => ctrl.abort(), cfg.timeoutMs);
|
|
30
|
+
try {
|
|
31
|
+
const res = await fetch(url, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: {
|
|
34
|
+
Authorization: `Bearer ${cfg.apiKey}`,
|
|
35
|
+
'Content-Type': 'application/json',
|
|
36
|
+
},
|
|
37
|
+
body: JSON.stringify({
|
|
38
|
+
model: cfg.model,
|
|
39
|
+
messages: [
|
|
40
|
+
{ role: 'system', content: systemMsg },
|
|
41
|
+
{ role: 'user', content: userMsg },
|
|
42
|
+
],
|
|
43
|
+
max_tokens: cfg.maxTokens,
|
|
44
|
+
temperature: cfg.temperature,
|
|
45
|
+
}),
|
|
46
|
+
signal: ctrl.signal,
|
|
47
|
+
});
|
|
48
|
+
if (!res.ok) {
|
|
49
|
+
const text = await res.text().catch(() => '<no body>');
|
|
50
|
+
throw new Error(`LLM POST ${res.status}: ${text.slice(0, 500)}`);
|
|
51
|
+
}
|
|
52
|
+
const json = (await res.json());
|
|
53
|
+
const content = json.choices?.[0]?.message?.content ?? '';
|
|
54
|
+
if (!content)
|
|
55
|
+
throw new Error('LLM response had empty content');
|
|
56
|
+
return { content, model: json.model ?? cfg.model };
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/main.d.ts
ADDED
package/dist/main.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
// atrib-summarize standalone binary. Wires the McpServer to a stdio transport
|
|
4
|
+
// so it can be launched as a subprocess by an MCP host (Claude Code,
|
|
5
|
+
// Claude Desktop, etc.).
|
|
6
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
|
+
import { createAtribSummarizeServer } from './index.js';
|
|
8
|
+
async function main() {
|
|
9
|
+
const { mcp } = await createAtribSummarizeServer();
|
|
10
|
+
const transport = new StdioServerTransport();
|
|
11
|
+
await mcp.connect(transport);
|
|
12
|
+
}
|
|
13
|
+
main().catch((e) => {
|
|
14
|
+
console.error('atrib-summarize: fatal', e instanceof Error ? e.stack ?? e.message : String(e));
|
|
15
|
+
process.exit(1);
|
|
16
|
+
});
|
package/dist/prompt.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Prompt construction for the summarize tool.
|
|
3
|
+
*
|
|
4
|
+
* Renders a chronological prose digest of N records and feeds it to an
|
|
5
|
+
* LLM with instructions to synthesize a narrative. The records' semantic
|
|
6
|
+
* content (from the local sidecar) is included when available; legacy
|
|
7
|
+
* bare-record entries fall back to event_type + cryptographic metadata
|
|
8
|
+
* only, with a flag so the LLM knows the input is impoverished.
|
|
9
|
+
*/
|
|
10
|
+
import type { IndexedRecord } from './storage.js';
|
|
11
|
+
export declare function buildSystemPrompt(): string;
|
|
12
|
+
/**
|
|
13
|
+
* Render the user message: a chronological digest of every record fed
|
|
14
|
+
* to the LLM, followed by the focus question (if any).
|
|
15
|
+
*/
|
|
16
|
+
export declare function buildUserMessage(records: IndexedRecord[], focus: string | undefined): string;
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
const SYSTEM_PROMPT = `You synthesize narratives across signed agent activity records.
|
|
3
|
+
|
|
4
|
+
Each record has:
|
|
5
|
+
- A cryptographic identity (signature, hash, creator_key)
|
|
6
|
+
- A causal position (chain_root, informed_by)
|
|
7
|
+
- A semantic payload, EITHER carried in a local sidecar (rich) OR absent (impoverished, only event_type and metadata)
|
|
8
|
+
|
|
9
|
+
Your job: produce a coherent narrative across the records that surfaces:
|
|
10
|
+
- What the agent was doing (decisions, observations, revisions)
|
|
11
|
+
- What informed what (causal chains via informed_by)
|
|
12
|
+
- What's load-bearing vs incidental
|
|
13
|
+
- Honest gaps (when records are impoverished, say so; do not invent semantics)
|
|
14
|
+
|
|
15
|
+
Cite specific records by short hash (first 12 chars of record_hash) when making claims.
|
|
16
|
+
Be concise. The reader is the same agent that signed these records — assume they want to be reminded, not lectured.`;
|
|
17
|
+
export function buildSystemPrompt() {
|
|
18
|
+
return SYSTEM_PROMPT;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Render the user message: a chronological digest of every record fed
|
|
22
|
+
* to the LLM, followed by the focus question (if any).
|
|
23
|
+
*/
|
|
24
|
+
export function buildUserMessage(records, focus) {
|
|
25
|
+
const sortedAsc = [...records].sort((a, b) => a.record.timestamp - b.record.timestamp);
|
|
26
|
+
const lines = [];
|
|
27
|
+
lines.push(`# Records to synthesize (${records.length}, oldest-first)`);
|
|
28
|
+
lines.push('');
|
|
29
|
+
for (const r of sortedAsc) {
|
|
30
|
+
lines.push(renderRecord(r));
|
|
31
|
+
lines.push('');
|
|
32
|
+
}
|
|
33
|
+
lines.push('---');
|
|
34
|
+
lines.push('');
|
|
35
|
+
if (focus && focus.trim().length > 0) {
|
|
36
|
+
lines.push(`# Focus`);
|
|
37
|
+
lines.push(focus.trim());
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
lines.push(`# Default focus`);
|
|
41
|
+
lines.push('Summarize what the agent did and why, surfacing the load-bearing decisions and the causal chain.');
|
|
42
|
+
}
|
|
43
|
+
return lines.join('\n');
|
|
44
|
+
}
|
|
45
|
+
function shortHash(h) {
|
|
46
|
+
// strip "sha256:" prefix and shorten
|
|
47
|
+
const noPrefix = h.startsWith('sha256:') ? h.slice(7) : h;
|
|
48
|
+
return noPrefix.slice(0, 12) + '…';
|
|
49
|
+
}
|
|
50
|
+
function renderRecord(r) {
|
|
51
|
+
const ts = new Date(r.record.timestamp).toISOString();
|
|
52
|
+
const evt = r.record.event_type.split('/').pop() ?? r.record.event_type;
|
|
53
|
+
const hashShort = shortHash(r.record_hash);
|
|
54
|
+
const ctxShort = r.record.context_id.slice(0, 8) + '…';
|
|
55
|
+
const informedBy = Array.isArray(r.record.informed_by) ? r.record.informed_by : [];
|
|
56
|
+
const out = [];
|
|
57
|
+
out.push(`## ${ts} · ${evt} · ${hashShort} · trace ${ctxShort}`);
|
|
58
|
+
if (informedBy.length > 0) {
|
|
59
|
+
out.push(`informed_by: ${informedBy.map(shortHash).join(', ')}`);
|
|
60
|
+
}
|
|
61
|
+
const sc = r.local;
|
|
62
|
+
if (sc) {
|
|
63
|
+
if (sc.toolName)
|
|
64
|
+
out.push(`tool: ${sc.toolName}`);
|
|
65
|
+
const c = sc.content;
|
|
66
|
+
if (c) {
|
|
67
|
+
if (typeof c['what'] === 'string')
|
|
68
|
+
out.push(`what: ${c['what']}`);
|
|
69
|
+
if (typeof c['why_noted'] === 'string')
|
|
70
|
+
out.push(`why_noted: ${c['why_noted']}`);
|
|
71
|
+
if (typeof c['summary'] === 'string')
|
|
72
|
+
out.push(`summary: ${c['summary']}`);
|
|
73
|
+
if (typeof c['importance'] === 'string')
|
|
74
|
+
out.push(`importance: ${c['importance']}`);
|
|
75
|
+
if (typeof c['prior_position'] === 'string')
|
|
76
|
+
out.push(`prior_position: ${c['prior_position']}`);
|
|
77
|
+
if (typeof c['new_position'] === 'string')
|
|
78
|
+
out.push(`new_position: ${c['new_position']}`);
|
|
79
|
+
if (typeof c['reason'] === 'string')
|
|
80
|
+
out.push(`reason: ${c['reason']}`);
|
|
81
|
+
if (Array.isArray(c['topics'])) {
|
|
82
|
+
out.push(`topics: ${c['topics'].filter((x) => typeof x === 'string').join(', ')}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Tool-call sidecar may have args/result; keep brief to control prompt size.
|
|
86
|
+
if (sc.args)
|
|
87
|
+
out.push(`args (truncated): ${JSON.stringify(sc.args).slice(0, 300)}`);
|
|
88
|
+
if (sc.result)
|
|
89
|
+
out.push(`result (truncated): ${JSON.stringify(sc.result).slice(0, 300)}`);
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
out.push('(no semantic sidecar available — record predates local-mirror sidecar pattern; only cryptographic metadata is present)');
|
|
93
|
+
}
|
|
94
|
+
return out.join('\n');
|
|
95
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type AtribRecord, type OnRecordSidecar } from '@atrib/mcp';
|
|
2
|
+
export interface IndexedRecord {
|
|
3
|
+
record: AtribRecord;
|
|
4
|
+
/** sha256:<64-hex> form, matching informed_by entries. */
|
|
5
|
+
record_hash: string;
|
|
6
|
+
/** Source file the record was read from (for debugging). */
|
|
7
|
+
source: string;
|
|
8
|
+
/**
|
|
9
|
+
* Pre-sign payload context, when the producer wrote it to the local
|
|
10
|
+
* mirror as a `_local` sidecar on the envelope. Carries semantic content
|
|
11
|
+
* (toolName, args, result, content) the signed AtribRecord COMMITS TO
|
|
12
|
+
* via content_id / args_hash / result_hash but does not itself contain.
|
|
13
|
+
* Absent on legacy bare-record entries from older mirror writes.
|
|
14
|
+
*/
|
|
15
|
+
local?: SidecarPayload;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Combined sidecar shape — superset of every producer's local payload
|
|
19
|
+
* (mcp-wrap writes toolName/args/result; atrib-emit writes content).
|
|
20
|
+
*/
|
|
21
|
+
export interface SidecarPayload extends OnRecordSidecar {
|
|
22
|
+
content?: Record<string, unknown>;
|
|
23
|
+
producer?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Read every *.jsonl mirror in ATRIB_RECORDS_DIR and return an index keyed
|
|
27
|
+
* by sha256:<64-hex> record_hash. Both shapes (bare AtribRecord and emit's
|
|
28
|
+
* { record, proof, written_at } envelope) are supported.
|
|
29
|
+
*
|
|
30
|
+
* Returns the indexed map AND a flat list (newest-first by timestamp) for
|
|
31
|
+
* callers that want recall-style enumeration without by-hash lookup.
|
|
32
|
+
*/
|
|
33
|
+
export declare function loadAllRecords(dir?: string): {
|
|
34
|
+
byHash: Map<string, IndexedRecord>;
|
|
35
|
+
newestFirst: IndexedRecord[];
|
|
36
|
+
};
|
package/dist/storage.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
/**
|
|
3
|
+
* Local mirror reader for atrib-trace.
|
|
4
|
+
*
|
|
5
|
+
* Reads every *.jsonl mirror under ~/.atrib/records/ and normalizes to bare
|
|
6
|
+
* AtribRecord shape regardless of producer (wrapper-signed or emit envelope).
|
|
7
|
+
*
|
|
8
|
+
* Builds an in-memory index by record_hash so trace can walk informed_by
|
|
9
|
+
* chains in O(1) per hop. The hash key is sha256:<64-hex> (the same form
|
|
10
|
+
* informed_by entries use), so no transformation needed at lookup time.
|
|
11
|
+
*/
|
|
12
|
+
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
|
13
|
+
import { homedir } from 'node:os';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { canonicalRecord, hexEncode, sha256 } from '@atrib/mcp';
|
|
16
|
+
const RECORDS_DIR = process.env.ATRIB_RECORDS_DIR ?? join(homedir(), '.atrib', 'records');
|
|
17
|
+
/**
|
|
18
|
+
* Read every *.jsonl mirror in ATRIB_RECORDS_DIR and return an index keyed
|
|
19
|
+
* by sha256:<64-hex> record_hash. Both shapes (bare AtribRecord and emit's
|
|
20
|
+
* { record, proof, written_at } envelope) are supported.
|
|
21
|
+
*
|
|
22
|
+
* Returns the indexed map AND a flat list (newest-first by timestamp) for
|
|
23
|
+
* callers that want recall-style enumeration without by-hash lookup.
|
|
24
|
+
*/
|
|
25
|
+
export function loadAllRecords(dir = RECORDS_DIR) {
|
|
26
|
+
const byHash = new Map();
|
|
27
|
+
const all = [];
|
|
28
|
+
if (!existsSync(dir))
|
|
29
|
+
return { byHash, newestFirst: [] };
|
|
30
|
+
let files = [];
|
|
31
|
+
try {
|
|
32
|
+
files = readdirSync(dir).filter((f) => f.endsWith('.jsonl'));
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return { byHash, newestFirst: [] };
|
|
36
|
+
}
|
|
37
|
+
for (const fname of files) {
|
|
38
|
+
const path = join(dir, fname);
|
|
39
|
+
try {
|
|
40
|
+
const raw = readFileSync(path, 'utf8');
|
|
41
|
+
for (const line of raw.split('\n')) {
|
|
42
|
+
const trimmed = line.trim();
|
|
43
|
+
if (!trimmed)
|
|
44
|
+
continue;
|
|
45
|
+
try {
|
|
46
|
+
const parsed = JSON.parse(trimmed);
|
|
47
|
+
// Normalize: envelope shape vs legacy bare record shape.
|
|
48
|
+
const isEnvelope = 'record' in parsed &&
|
|
49
|
+
parsed.record &&
|
|
50
|
+
parsed.record.context_id !== undefined;
|
|
51
|
+
const rec = isEnvelope
|
|
52
|
+
? parsed.record
|
|
53
|
+
: parsed;
|
|
54
|
+
if (!rec.context_id || !rec.signature || !rec.timestamp)
|
|
55
|
+
continue;
|
|
56
|
+
const hashHex = hexEncode(sha256(canonicalRecord(rec)));
|
|
57
|
+
const indexed = {
|
|
58
|
+
record: rec,
|
|
59
|
+
record_hash: `sha256:${hashHex}`,
|
|
60
|
+
source: fname,
|
|
61
|
+
};
|
|
62
|
+
// Lift the `_local` sidecar onto the indexed record when present.
|
|
63
|
+
// Legacy bare-record entries have no sidecar; that's OK — consumers
|
|
64
|
+
// tolerate its absence.
|
|
65
|
+
if (isEnvelope) {
|
|
66
|
+
const sidecar = parsed._local;
|
|
67
|
+
if (sidecar)
|
|
68
|
+
indexed.local = sidecar;
|
|
69
|
+
}
|
|
70
|
+
byHash.set(indexed.record_hash, indexed);
|
|
71
|
+
all.push(indexed);
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// Malformed line; skip.
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
// File read failure; skip this file.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
all.sort((a, b) => b.record.timestamp - a.record.timestamp);
|
|
83
|
+
return { byHash, newestFirst: all };
|
|
84
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@atrib/summarize",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "MCP server for atrib. Synthesizes a narrative across N records via an OpenAI-compatible LLM so agents read context, not raw record bytes.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"bin": {
|
|
9
|
+
"atrib-summarize": "./dist/main.js"
|
|
10
|
+
},
|
|
11
|
+
"dependencies": {
|
|
12
|
+
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
13
|
+
"zod": "^3.25.76",
|
|
14
|
+
"@atrib/mcp": "0.4.0"
|
|
15
|
+
},
|
|
16
|
+
"devDependencies": {
|
|
17
|
+
"@types/node": "^22.19.17",
|
|
18
|
+
"tsx": "^4.21.0",
|
|
19
|
+
"typescript": "^5.9.3",
|
|
20
|
+
"vitest": "^3.2.4"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist"
|
|
24
|
+
],
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "rm -rf dist && tsc",
|
|
30
|
+
"start": "node dist/main.js",
|
|
31
|
+
"dev": "tsx src/main.ts",
|
|
32
|
+
"test": "vitest run"
|
|
33
|
+
}
|
|
34
|
+
}
|