@weaveaijs/mcp-observatory 0.3.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.
Files changed (92) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +322 -0
  3. package/dist/core/context.d.ts +46 -0
  4. package/dist/core/context.d.ts.map +1 -0
  5. package/dist/core/context.js +38 -0
  6. package/dist/core/context.js.map +1 -0
  7. package/dist/core/tracer.d.ts +17 -0
  8. package/dist/core/tracer.d.ts.map +1 -0
  9. package/dist/core/tracer.js +29 -0
  10. package/dist/core/tracer.js.map +1 -0
  11. package/dist/core/wrapper.d.ts +34 -0
  12. package/dist/core/wrapper.d.ts.map +1 -0
  13. package/dist/core/wrapper.js +93 -0
  14. package/dist/core/wrapper.js.map +1 -0
  15. package/dist/cost/pricing.d.ts +6 -0
  16. package/dist/cost/pricing.d.ts.map +1 -0
  17. package/dist/cost/pricing.js +21 -0
  18. package/dist/cost/pricing.js.map +1 -0
  19. package/dist/cost/tokenizer.d.ts +7 -0
  20. package/dist/cost/tokenizer.d.ts.map +1 -0
  21. package/dist/cost/tokenizer.js +25 -0
  22. package/dist/cost/tokenizer.js.map +1 -0
  23. package/dist/demo/client.d.ts +18 -0
  24. package/dist/demo/client.d.ts.map +1 -0
  25. package/dist/demo/client.js +57 -0
  26. package/dist/demo/client.js.map +1 -0
  27. package/dist/demo/runDemo.d.ts +2 -0
  28. package/dist/demo/runDemo.d.ts.map +1 -0
  29. package/dist/demo/runDemo.js +15 -0
  30. package/dist/demo/runDemo.js.map +1 -0
  31. package/dist/demo/server.d.ts +19 -0
  32. package/dist/demo/server.d.ts.map +1 -0
  33. package/dist/demo/server.js +100 -0
  34. package/dist/demo/server.js.map +1 -0
  35. package/dist/hallucination/scoring.d.ts +14 -0
  36. package/dist/hallucination/scoring.d.ts.map +1 -0
  37. package/dist/hallucination/scoring.js +67 -0
  38. package/dist/hallucination/scoring.js.map +1 -0
  39. package/dist/index.d.ts +20 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +23 -0
  42. package/dist/index.js.map +1 -0
  43. package/dist/proposal/proposer.d.ts +30 -0
  44. package/dist/proposal/proposer.d.ts.map +1 -0
  45. package/dist/proposal/proposer.js +73 -0
  46. package/dist/proposal/proposer.js.map +1 -0
  47. package/dist/proposal/storage.d.ts +38 -0
  48. package/dist/proposal/storage.d.ts.map +1 -0
  49. package/dist/proposal/storage.js +115 -0
  50. package/dist/proposal/storage.js.map +1 -0
  51. package/dist/proposal/token.d.ts +34 -0
  52. package/dist/proposal/token.d.ts.map +1 -0
  53. package/dist/proposal/token.js +52 -0
  54. package/dist/proposal/token.js.map +1 -0
  55. package/dist/proposal/verifier.d.ts +20 -0
  56. package/dist/proposal/verifier.d.ts.map +1 -0
  57. package/dist/proposal/verifier.js +34 -0
  58. package/dist/proposal/verifier.js.map +1 -0
  59. package/dist/risk/scoring.d.ts +11 -0
  60. package/dist/risk/scoring.d.ts.map +1 -0
  61. package/dist/risk/scoring.js +54 -0
  62. package/dist/risk/scoring.js.map +1 -0
  63. package/dist/tests/hashing.test.d.ts +2 -0
  64. package/dist/tests/hashing.test.d.ts.map +1 -0
  65. package/dist/tests/hashing.test.js +39 -0
  66. package/dist/tests/hashing.test.js.map +1 -0
  67. package/dist/tests/proposer.test.d.ts +2 -0
  68. package/dist/tests/proposer.test.d.ts.map +1 -0
  69. package/dist/tests/proposer.test.js +49 -0
  70. package/dist/tests/proposer.test.js.map +1 -0
  71. package/dist/tests/scoring.test.d.ts +2 -0
  72. package/dist/tests/scoring.test.d.ts.map +1 -0
  73. package/dist/tests/scoring.test.js +41 -0
  74. package/dist/tests/scoring.test.js.map +1 -0
  75. package/dist/tests/token.test.d.ts +2 -0
  76. package/dist/tests/token.test.d.ts.map +1 -0
  77. package/dist/tests/token.test.js +51 -0
  78. package/dist/tests/token.test.js.map +1 -0
  79. package/dist/tests/tracer.test.d.ts +2 -0
  80. package/dist/tests/tracer.test.d.ts.map +1 -0
  81. package/dist/tests/tracer.test.js +38 -0
  82. package/dist/tests/tracer.test.js.map +1 -0
  83. package/dist/utils/hashing.d.ts +5 -0
  84. package/dist/utils/hashing.d.ts.map +1 -0
  85. package/dist/utils/hashing.js +18 -0
  86. package/dist/utils/hashing.js.map +1 -0
  87. package/dist/utils/time.d.ts +6 -0
  88. package/dist/utils/time.d.ts.map +1 -0
  89. package/dist/utils/time.js +22 -0
  90. package/dist/utils/time.js.map +1 -0
  91. package/package.json +63 -0
  92. package/sql/schema.sql +73 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,322 @@
1
+ # MCP Observatory - Node.js Edition
2
+
3
+ A modern TypeScript/Node.js implementation of an observability and APM toolkit for MCP (Model Context Protocol) servers, featuring a two-phase execution pattern for high-risk tool calls.
4
+
5
+ ## Overview
6
+
7
+ MCP Observatory provides:
8
+
9
+ 1. **Tracer & Observability**: Track spans, tokens, costs, and latency for every operation
10
+ 2. **Proposal/Commit Pattern**: Two-phase execution for high-risk operations with deterministic fallbacks
11
+ 3. **Risk Assessment**: Hallucination scoring, tool risk categorization, and numeric variance detection
12
+ 4. **Cost Tracking**: Token estimation and model-aware pricing for various AI providers
13
+ 5. **Storage Options**: In-memory or PostgreSQL-backed proposal/commit storage
14
+
15
+ ## Architecture
16
+
17
+ ```
18
+ ┌─ Core Layer
19
+ │ ├─ Tracer: Span creation and lifecycle management
20
+ │ ├─ TraceContext: Span data model with metrics
21
+ │ └─ InvocationWrapper: Policy-driven execution wrapper
22
+
23
+ ├─ Proposal/Commit Layer
24
+ │ ├─ ToolProposer: Risk scoring and proposal generation
25
+ │ ├─ TokenManager: HMAC-signed token issue/verify
26
+ │ ├─ CommitVerifier: Multi-stage verification with replay protection
27
+ │ └─ Storage: In-memory or PostgreSQL backends
28
+
29
+ ├─ Assessment Layer
30
+ │ ├─ Hallucination Scoring: Output instability, grounding, variance
31
+ │ ├─ Risk Scoring: Tool classification by destructiveness/scope
32
+ │ └─ Hashing: Stable canonical JSON and prompt normalization
33
+
34
+ └─ Demo Layer
35
+ ├─ MCPServer: Example server with propose/commit handlers
36
+ └─ MCPClient: Example client with dual-measurement support
37
+ ```
38
+
39
+ ## Quick Start
40
+
41
+ ### Installation
42
+
43
+ ```bash
44
+ npm install
45
+ npm run build
46
+ ```
47
+
48
+ ### Running the Demo
49
+
50
+ ```bash
51
+ # Without database
52
+ npm run demo
53
+
54
+ # With PostgreSQL (optional)
55
+ export MCP_OBSERVATORY_PG_DSN='postgresql://user:pass@localhost:5432/postgres'
56
+ psql "$MCP_OBSERVATORY_PG_DSN" -f sql/schema.sql
57
+ npm run demo
58
+ ```
59
+
60
+ ### Running Tests
61
+
62
+ ```bash
63
+ npm test
64
+ ```
65
+
66
+ ## Core Concepts
67
+
68
+ ### Spans & Tracing
69
+
70
+ Track execution metrics for any operation:
71
+
72
+ ```typescript
73
+ import { Tracer } from 'mcp-observatory';
74
+
75
+ const tracer = new Tracer('my-service');
76
+
77
+ await tracer.withSpan(async (span) => {
78
+ span.inputTokens = 150;
79
+ span.outputTokens = 250;
80
+ span.costUsd = 0.0045;
81
+
82
+ // Your async operation here
83
+ }, { model: 'gpt-4o' });
84
+ ```
85
+
86
+ ### Two-Phase Execution
87
+
88
+ For high-risk operations, use propose/commit pattern:
89
+
90
+ ```typescript
91
+ import { ToolProposer, CommitVerifier } from 'mcp-observatory';
92
+
93
+ const proposer = new ToolProposer();
94
+ const verifier = new CommitVerifier();
95
+
96
+ // Phase 1: Propose (no side effects)
97
+ const proposal = await proposer.propose({
98
+ toolName: 'transfer_funds',
99
+ toolArgs: { amount: 1000, to: 'account_456' },
100
+ outputInstability: 0.3,
101
+ });
102
+
103
+ // Response includes commit token
104
+ console.log(proposal.status); // 'allowed' | 'blocked' | 'review'
105
+
106
+ // Phase 2: Commit (only if proposal token is valid)
107
+ if (proposal.commitToken) {
108
+ const verification = verifier.verify({
109
+ token: proposal.commitToken,
110
+ proposalId: proposal.proposalId,
111
+ toolName: 'transfer_funds',
112
+ toolArgs: { amount: 1000, to: 'account_456' },
113
+ });
114
+
115
+ if (verification.canExecute) {
116
+ // Execute the operation
117
+ }
118
+ }
119
+ ```
120
+
121
+ ### Risk Assessment
122
+
123
+ Compute composite risk scores from multiple signals:
124
+
125
+ ```typescript
126
+ import {
127
+ computeHallucinationRiskScore,
128
+ computeRiskScore,
129
+ categorizeRisk,
130
+ } from 'mcp-observatory';
131
+
132
+ // Hallucination risk
133
+ const hallucScore = computeHallucinationRiskScore({
134
+ outputInstability: 0.4,
135
+ groundingScore: 0.7,
136
+ numericVarianceScore: 0.1,
137
+ selfConsistencyScore: 0.9,
138
+ toolClaimMismatch: false,
139
+ });
140
+
141
+ // Tool risk categorization
142
+ const signals = categorizeRisk('delete_user', {});
143
+ const riskScore = computeRiskScore(signals);
144
+ ```
145
+
146
+ ### Cost Tracking
147
+
148
+ Estimate tokens and costs across models:
149
+
150
+ ```typescript
151
+ import { estimateTokens, estimateCost, getPricing } from 'mcp-observatory';
152
+
153
+ const text = 'Generate a deployment plan';
154
+ const tokens = estimateTokens(text, 'gpt-4o');
155
+ const cost = estimateCost(tokens, 'gpt-4o', 'model');
156
+
157
+ console.log(`Tokens: ${tokens}, Cost: $${cost.toFixed(4)}`);
158
+ ```
159
+
160
+ ## Advanced Features
161
+
162
+ ### Dual Measurement (Shadow Runs)
163
+
164
+ Compare two execution paths:
165
+
166
+ ```typescript
167
+ import { InvocationWrapper } from 'mcp-observatory';
168
+
169
+ const wrapper = new InvocationWrapper('my-service');
170
+
171
+ const result = await wrapper.invoke({
172
+ source: 'agent',
173
+ model: 'gpt-4o',
174
+ prompt: 'Analyze this request',
175
+ call: () => primaryCall(),
176
+ dualInvoke: true,
177
+ shadowCall: () => shadowCall(),
178
+ });
179
+
180
+ console.log(`Primary cost: $${result.span.costUsd}`);
181
+ console.log(`Shadow cost: $${result.shadowSpan?.costUsd}`);
182
+ ```
183
+
184
+ ### Storage Options
185
+
186
+ #### In-Memory (Default)
187
+
188
+ ```typescript
189
+ import { InMemoryProposalStorage } from 'mcp-observatory';
190
+
191
+ const storage = new InMemoryProposalStorage();
192
+ ```
193
+
194
+ #### PostgreSQL
195
+
196
+ ```typescript
197
+ import { PostgresProposalStorage } from 'mcp-observatory';
198
+
199
+ const storage = new PostgresProposalStorage(
200
+ process.env.MCP_OBSERVATORY_PG_DSN!
201
+ );
202
+
203
+ // Later
204
+ await storage.close();
205
+ ```
206
+
207
+ ## Module Reference
208
+
209
+ ### Core (`src/core`)
210
+
211
+ - **`tracer.ts`**: Span creation and lifecycle
212
+ - **`context.ts`**: TraceContext data model with metrics
213
+ - **`wrapper.ts`**: InvocationWrapper with policy decisioning
214
+
215
+ ### Proposal/Commit (`src/proposal`)
216
+
217
+ - **`token.ts`**: TokenManager for HMAC-signed token issue/verify
218
+ - **`proposer.ts`**: ToolProposer with risk-based decisioning
219
+ - **`verifier.ts`**: CommitVerifier with replay protection
220
+ - **`storage.ts`**: In-memory and PostgreSQL storage backends
221
+
222
+ ### Assessment (`src/hallucination`, `src/risk`)
223
+
224
+ - **`scoring.ts`** (hallucination): Risk scoring from instability, grounding, variance
225
+ - **`scoring.ts`** (risk): Tool risk categorization by destructiveness/scope
226
+
227
+ ### Utilities (`src/utils`, `src/cost`)
228
+
229
+ - **`hashing.ts`**: Stable canonical JSON and prompt normalization
230
+ - **`time.ts`**: Time utilities
231
+ - **`tokenizer.ts`**: Token estimation with model-specific limits
232
+ - **`pricing.ts`**: Cost estimation for GPT and Claude models
233
+
234
+ ### Demo (`src/demo`)
235
+
236
+ - **`server.ts`**: Example MCP server with propose/commit handlers
237
+ - **`client.ts`**: Example client with dual-measurement support
238
+
239
+ ## Testing
240
+
241
+ ```bash
242
+ npm test
243
+ ```
244
+
245
+ Tests include:
246
+
247
+ - Tracer span creation and inheritance
248
+ - Token issuance, verification, and expiry
249
+ - Proposal scoring and status determination
250
+ - Hash stability and prompt normalization
251
+ - Risk and hallucination scoring
252
+
253
+ ## API Endpoints (Demo Server)
254
+
255
+ The demo server exposes:
256
+
257
+ - `transfer_funds_propose(amount, to)` → {proposalId, status, commitToken?}
258
+ - `transfer_funds_commit(proposalId, commitToken, amount, to)` → {success, transactionId?}
259
+
260
+ ## Security Rules
261
+
262
+ Commit verification enforces:
263
+
264
+ 1. ✅ Token signature is valid
265
+ 2. ✅ Token not expired (5-minute default)
266
+ 3. ✅ Proposal exists and matches proposal_id
267
+ 4. ✅ Tool name matches token payload
268
+ 5. ✅ Args hash matches token payload (prevents tampering)
269
+ 6. ✅ Nonce not already used (replay protection)
270
+
271
+ ## Database Setup (Optional)
272
+
273
+ Apply schema to existing PostgreSQL database:
274
+
275
+ ```bash
276
+ export MCP_OBSERVATORY_PG_DSN='postgresql://user:pass@localhost:5432/postgres'
277
+ psql "$MCP_OBSERVATORY_PG_DSN" -f sql/schema.sql
278
+ ```
279
+
280
+ Schema includes:
281
+
282
+ - `proposals`: Proposal records with status and expiration
283
+ - `commits`: Execution tracking with timestamps
284
+ - `nonces`: Used nonces for replay prevention
285
+ - `tool_prompt_baselines`: Prompt drift baseline storage
286
+ - `traces`: Full execution traces with span hierarchy
287
+ - `cleanup_expired_proposals()`: Automated cleanup function
288
+
289
+ ## Environment Variables
290
+
291
+ - `MCP_OBSERVATORY_PG_DSN`: PostgreSQL connection string (optional)
292
+ - `NODE_ENV`: Set to `production` for optimized builds
293
+
294
+ ## Build & Development
295
+
296
+ ```bash
297
+ npm run build # Compile TypeScript
298
+ npm run dev # Watch mode
299
+ npm run lint # Lint with ESLint
300
+ npm test # Run tests
301
+ npm run demo # Run demo
302
+ ```
303
+
304
+ ## License
305
+
306
+ Apache License 2.0 (see LICENSE file)
307
+
308
+ ## Architecture Preservation
309
+
310
+ This Node.js rewrite preserves the original Python architecture:
311
+
312
+ - ✅ Core tracer and span model
313
+ - ✅ Two-phase proposal/commit pattern
314
+ - ✅ HMAC-signed token verification
315
+ - ✅ Multi-stage risk scoring
316
+ - ✅ Storage abstraction (in-memory + PostgreSQL)
317
+ - ✅ Hallucination detection signals
318
+ - ✅ Cost and token tracking
319
+ - ✅ Demo applications
320
+ - ✅ Test coverage
321
+
322
+ The module structure and API interfaces remain consistent, enabling code reuse and knowledge transfer between Python and Node.js implementations.
@@ -0,0 +1,46 @@
1
+ export interface TraceSpan {
2
+ spanId: string;
3
+ traceId: string;
4
+ parentSpanId?: string;
5
+ service: string;
6
+ model?: string;
7
+ toolName?: string;
8
+ startTime: Date;
9
+ endTime?: Date;
10
+ inputHash?: string;
11
+ outputHash?: string;
12
+ inputTokens?: number;
13
+ outputTokens?: number;
14
+ totalTokens?: number;
15
+ costUsd?: number;
16
+ statusCode?: number;
17
+ tags?: Record<string, string | number | boolean>;
18
+ }
19
+ export declare class TraceContext {
20
+ readonly spanId: string;
21
+ readonly traceId: string;
22
+ readonly parentSpanId?: string;
23
+ readonly service: string;
24
+ readonly model?: string;
25
+ readonly toolName?: string;
26
+ readonly startTime: Date;
27
+ endTime?: Date;
28
+ inputHash?: string;
29
+ outputHash?: string;
30
+ inputTokens?: number;
31
+ outputTokens?: number;
32
+ totalTokens?: number;
33
+ costUsd: number;
34
+ statusCode?: number;
35
+ tags: Record<string, string | number | boolean>;
36
+ constructor(options: {
37
+ service: string;
38
+ model?: string;
39
+ toolName?: string;
40
+ traceId?: string;
41
+ parentSpanId?: string;
42
+ });
43
+ finish(): void;
44
+ toJSON(): TraceSpan;
45
+ }
46
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/core/context.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,SAAS;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,IAAI,CAAC;IAChB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;CAClD;AAED,qBAAa,YAAY;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,OAAO,CAAC,EAAE,IAAI,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAK;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAM;gBAEzC,OAAO,EAAE;QACnB,OAAO,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB;IAUD,MAAM,IAAI,IAAI;IAId,MAAM,IAAI,SAAS;CAoBpB"}
@@ -0,0 +1,38 @@
1
+ import { randomUUID } from 'crypto';
2
+ export class TraceContext {
3
+ constructor(options) {
4
+ this.costUsd = 0;
5
+ this.tags = {};
6
+ this.spanId = randomUUID();
7
+ this.traceId = options.traceId || randomUUID();
8
+ this.parentSpanId = options.parentSpanId;
9
+ this.service = options.service;
10
+ this.model = options.model;
11
+ this.toolName = options.toolName;
12
+ this.startTime = new Date();
13
+ }
14
+ finish() {
15
+ this.endTime = new Date();
16
+ }
17
+ toJSON() {
18
+ return {
19
+ spanId: this.spanId,
20
+ traceId: this.traceId,
21
+ parentSpanId: this.parentSpanId,
22
+ service: this.service,
23
+ model: this.model,
24
+ toolName: this.toolName,
25
+ startTime: this.startTime,
26
+ endTime: this.endTime,
27
+ inputHash: this.inputHash,
28
+ outputHash: this.outputHash,
29
+ inputTokens: this.inputTokens,
30
+ outputTokens: this.outputTokens,
31
+ totalTokens: this.totalTokens,
32
+ costUsd: this.costUsd,
33
+ statusCode: this.statusCode,
34
+ tags: this.tags,
35
+ };
36
+ }
37
+ }
38
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/core/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAqBpC,MAAM,OAAO,YAAY;IAkBvB,YAAY,OAMX;QAVD,YAAO,GAAW,CAAC,CAAC;QAEpB,SAAI,GAA8C,EAAE,CAAC;QASnD,IAAI,CAAC,MAAM,GAAG,UAAU,EAAE,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,UAAU,EAAE,CAAC;QAC/C,IAAI,CAAC,YAAY,GAAG,OAAO,CAAC,YAAY,CAAC;QACzC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,SAAS,GAAG,IAAI,IAAI,EAAE,CAAC;IAC9B,CAAC;IAED,MAAM;QACJ,IAAI,CAAC,OAAO,GAAG,IAAI,IAAI,EAAE,CAAC;IAC5B,CAAC;IAED,MAAM;QACJ,OAAO;YACL,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,KAAK,EAAE,IAAI,CAAC,KAAK;YACjB,QAAQ,EAAE,IAAI,CAAC,QAAQ;YACvB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,SAAS,EAAE,IAAI,CAAC,SAAS;YACzB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,YAAY,EAAE,IAAI,CAAC,YAAY;YAC/B,WAAW,EAAE,IAAI,CAAC,WAAW;YAC7B,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,UAAU,EAAE,IAAI,CAAC,UAAU;YAC3B,IAAI,EAAE,IAAI,CAAC,IAAI;SAChB,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,17 @@
1
+ import { TraceContext } from './context.js';
2
+ export declare class Tracer {
3
+ readonly service: string;
4
+ constructor(service: string);
5
+ startSpan(options?: {
6
+ model?: string;
7
+ toolName?: string;
8
+ parent?: TraceContext;
9
+ }): TraceContext;
10
+ endSpan(span: TraceContext): TraceContext;
11
+ withSpan<T>(fn: (span: TraceContext) => Promise<T> | T, options?: {
12
+ model?: string;
13
+ toolName?: string;
14
+ parent?: TraceContext;
15
+ }): Promise<T>;
16
+ }
17
+ //# sourceMappingURL=tracer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.d.ts","sourceRoot":"","sources":["../../src/core/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,qBAAa,MAAM;IACL,QAAQ,CAAC,OAAO,EAAE,MAAM;gBAAf,OAAO,EAAE,MAAM;IAEpC,SAAS,CAAC,OAAO,CAAC,EAAE;QAClB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,MAAM,CAAC,EAAE,YAAY,CAAC;KACvB,GAAG,YAAY;IAUhB,OAAO,CAAC,IAAI,EAAE,YAAY,GAAG,YAAY;IAKnC,QAAQ,CAAC,CAAC,EACd,EAAE,EAAE,CAAC,IAAI,EAAE,YAAY,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,EAC1C,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,YAAY,CAAA;KAAE,GACrE,OAAO,CAAC,CAAC,CAAC;CAQd"}
@@ -0,0 +1,29 @@
1
+ import { TraceContext } from './context.js';
2
+ export class Tracer {
3
+ constructor(service) {
4
+ this.service = service;
5
+ }
6
+ startSpan(options) {
7
+ return new TraceContext({
8
+ service: this.service,
9
+ model: options?.model,
10
+ toolName: options?.toolName,
11
+ traceId: options?.parent?.traceId,
12
+ parentSpanId: options?.parent?.spanId,
13
+ });
14
+ }
15
+ endSpan(span) {
16
+ span.finish();
17
+ return span;
18
+ }
19
+ async withSpan(fn, options) {
20
+ const span = this.startSpan(options);
21
+ try {
22
+ return await fn(span);
23
+ }
24
+ finally {
25
+ this.endSpan(span);
26
+ }
27
+ }
28
+ }
29
+ //# sourceMappingURL=tracer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tracer.js","sourceRoot":"","sources":["../../src/core/tracer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,OAAO,MAAM;IACjB,YAAqB,OAAe;QAAf,YAAO,GAAP,OAAO,CAAQ;IAAG,CAAC;IAExC,SAAS,CAAC,OAIT;QACC,OAAO,IAAI,YAAY,CAAC;YACtB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,KAAK,EAAE,OAAO,EAAE,KAAK;YACrB,QAAQ,EAAE,OAAO,EAAE,QAAQ;YAC3B,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO;YACjC,YAAY,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM;SACtC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,CAAC,IAAkB;QACxB,IAAI,CAAC,MAAM,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,QAAQ,CACZ,EAA0C,EAC1C,OAAsE;QAEtE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;QACrC,IAAI,CAAC;YACH,OAAO,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC;QACxB,CAAC;gBAAS,CAAC;YACT,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;CACF"}