@tryvira/mcp 0.1.40 → 0.1.42
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 +10 -12
- package/dist/cli.js +57 -2115
- package/dist/index.d.ts +2 -310
- package/dist/index.js +3 -222
- package/package.json +3 -4
- package/dist/migrations/001_vnext_foundation.sql +0 -628
package/dist/index.d.ts
CHANGED
|
@@ -1,310 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
organizationId: string;
|
|
4
|
-
projectId: string;
|
|
5
|
-
environmentId: string;
|
|
6
|
-
/** Optional hierarchy identities carried when a composed authority is in scope. */
|
|
7
|
-
applicationId?: string | null;
|
|
8
|
-
workspaceId?: string | null;
|
|
9
|
-
userId?: string | null;
|
|
10
|
-
sessionId?: string | null;
|
|
11
|
-
/** Optional composed-authority binding carried by persistence boundaries. */
|
|
12
|
-
authorityDigest?: string | null;
|
|
13
|
-
authorityBindingDigest?: string | null;
|
|
14
|
-
authorityBindingVersion?: number | null;
|
|
15
|
-
}
|
|
16
|
-
export interface ScopedEntity extends Scope {
|
|
17
|
-
id: string;
|
|
18
|
-
}
|
|
19
|
-
export interface Policy extends ScopedEntity {
|
|
20
|
-
effect: 'allow' | 'deny';
|
|
21
|
-
revision: string;
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* The governed behavior boundary exposed by Vira's product model.
|
|
25
|
-
*
|
|
26
|
-
* `ControlPoint` was the pre-product name. Keep the type alias for persisted
|
|
27
|
-
* legacy adapters, but new domain code must use BehaviorPoint.
|
|
28
|
-
*/
|
|
29
|
-
export interface BehaviorPoint extends ScopedEntity {
|
|
30
|
-
}
|
|
31
|
-
/** @deprecated Use BehaviorPoint. This alias exists only at compatibility boundaries. */
|
|
32
|
-
export type ControlPoint = BehaviorPoint;
|
|
33
|
-
export interface BehaviorVariant extends ScopedEntity {
|
|
34
|
-
}
|
|
35
|
-
export interface Revision extends Scope {
|
|
36
|
-
id: string;
|
|
37
|
-
controlPointId: string;
|
|
38
|
-
variantId: string;
|
|
39
|
-
policyRevision: string;
|
|
40
|
-
immutable: true;
|
|
41
|
-
}
|
|
42
|
-
export interface ExecutionReceipt extends Scope {
|
|
43
|
-
id: string;
|
|
44
|
-
revisionId: string;
|
|
45
|
-
actorId: string;
|
|
46
|
-
idempotencyKey: string;
|
|
47
|
-
decision: string;
|
|
48
|
-
reason: string;
|
|
49
|
-
createdAt: string;
|
|
50
|
-
semanticTaskRef?: string;
|
|
51
|
-
semanticTaskVersion?: number;
|
|
52
|
-
semanticTaskDigest?: string;
|
|
53
|
-
authorityBindingDigest?: string;
|
|
54
|
-
authorityBindingVersion?: number;
|
|
55
|
-
}
|
|
56
|
-
export function assertSameScope(...items: readonly Scope[]): void;
|
|
57
|
-
export function issueRevision(scope: Scope, behaviorPoint: BehaviorPoint, policy: Policy, variant: BehaviorVariant, id: string): Revision;
|
|
58
|
-
export function makeReceipt(scope: Scope, revision: Revision, actorId: string, idempotencyKey: string, decision: string, reason: string): ExecutionReceipt;
|
|
59
|
-
}
|
|
60
|
-
declare module "domain/src/scope-composer" {
|
|
61
|
-
export function scopeDigest(scope: unknown): string;
|
|
62
|
-
export type ScopeLevel = 'platform' | 'organization' | 'project' | 'application' | 'workspace' | 'user' | 'session';
|
|
63
|
-
export interface HierarchicalScope {
|
|
64
|
-
level: ScopeLevel;
|
|
65
|
-
id: string;
|
|
66
|
-
parentId?: string;
|
|
67
|
-
}
|
|
68
|
-
export interface ScopeDelegation {
|
|
69
|
-
id: string;
|
|
70
|
-
issuerId: string;
|
|
71
|
-
subjectId: string;
|
|
72
|
-
fromLevel: ScopeLevel;
|
|
73
|
-
toLevel: ScopeLevel;
|
|
74
|
-
permissions: readonly string[];
|
|
75
|
-
expiresAt: string;
|
|
76
|
-
}
|
|
77
|
-
export interface CanonicalOrganizationScopeInput {
|
|
78
|
-
applicationId?: string | null;
|
|
79
|
-
workspaceId?: string | null;
|
|
80
|
-
userId?: string | null;
|
|
81
|
-
sessionId?: string | null;
|
|
82
|
-
}
|
|
83
|
-
/** Canonical serializer shared by organization intelligence and Teach boundaries. */
|
|
84
|
-
export function canonicalOrganizationScopeKeys(input: CanonicalOrganizationScopeInput): string[];
|
|
85
|
-
export interface ReferenceScopeDelegation extends ScopeDelegation {
|
|
86
|
-
stableKey: string;
|
|
87
|
-
parentAuthorityLevel: ScopeLevel;
|
|
88
|
-
childScopeKind: ScopeLevel;
|
|
89
|
-
childScopeDigest: string;
|
|
90
|
-
parentRevisionDigest: string;
|
|
91
|
-
/** Reference programs may narrow an exception to explicit effect kinds. */
|
|
92
|
-
exceptionEffectTypes?: readonly string[];
|
|
93
|
-
when: {
|
|
94
|
-
kind: 'all';
|
|
95
|
-
expressions: readonly [];
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
export interface ScopeCompositionConflict {
|
|
99
|
-
code: 'SCOPE_CHAIN_INVALID' | 'SCOPE_DELEGATION_CONFLICT' | 'SCOPE_REVISION_LEVEL_CONFLICT' | 'TEMPORAL_INVARIANT_CONFLICT' | 'TEMPORAL_TRANSITION_CONFLICT' | 'RECOVERY_CONFLICT' | 'ACTOR_OWNERSHIP_CONFLICT' | 'DEADLINE_CONFLICT';
|
|
100
|
-
delegationIds: readonly string[];
|
|
101
|
-
hard: true;
|
|
102
|
-
}
|
|
103
|
-
export interface EffectiveRevisionBinding {
|
|
104
|
-
id: string;
|
|
105
|
-
digest: string;
|
|
106
|
-
sourceRevisionSetDigest?: string;
|
|
107
|
-
ancestorHardAuthorityDigest?: string;
|
|
108
|
-
}
|
|
109
|
-
export interface ScopeBehaviorRevision {
|
|
110
|
-
id: string;
|
|
111
|
-
digest: string;
|
|
112
|
-
level: ScopeLevel;
|
|
113
|
-
hard: boolean;
|
|
114
|
-
source: string;
|
|
115
|
-
temporalInvariantDigest?: string;
|
|
116
|
-
temporalTransitionDigest?: string;
|
|
117
|
-
recoveryDigest?: string;
|
|
118
|
-
temporalInvariantKeys?: Readonly<Record<string, string>>;
|
|
119
|
-
temporalTransitionKeys?: Readonly<Record<string, string>>;
|
|
120
|
-
recoveryKeys?: Readonly<Record<string, string>>;
|
|
121
|
-
actorOwnershipDigest?: string;
|
|
122
|
-
deadlineDigest?: string;
|
|
123
|
-
}
|
|
124
|
-
export interface ScopeCompositionExplanation {
|
|
125
|
-
revisionId: string;
|
|
126
|
-
level: ScopeLevel;
|
|
127
|
-
disposition: 'inherited' | 'overridden' | 'rejected';
|
|
128
|
-
reason: string;
|
|
129
|
-
}
|
|
130
|
-
export interface ComposedScope {
|
|
131
|
-
chain: readonly HierarchicalScope[];
|
|
132
|
-
permissions: readonly string[];
|
|
133
|
-
delegationIds?: readonly string[];
|
|
134
|
-
compositionDigest: string;
|
|
135
|
-
conflictSetDigest: string;
|
|
136
|
-
conflictSummary: {
|
|
137
|
-
total: number;
|
|
138
|
-
hard: number;
|
|
139
|
-
soft: number;
|
|
140
|
-
byCategory: Record<string, number>;
|
|
141
|
-
};
|
|
142
|
-
conflicts: readonly ScopeCompositionConflict[];
|
|
143
|
-
serveable: boolean;
|
|
144
|
-
effectiveRevision?: EffectiveRevisionBinding;
|
|
145
|
-
sourceRevisions?: readonly ScopeBehaviorRevision[];
|
|
146
|
-
sourceRevisionSetDigest?: string;
|
|
147
|
-
ancestorHardAuthorityDigest?: string;
|
|
148
|
-
effectiveProgramDigest?: string;
|
|
149
|
-
explanations?: readonly ScopeCompositionExplanation[];
|
|
150
|
-
}
|
|
151
|
-
export function projectComposedScope(composed: ComposedScope): import("domain/src/vnext").Scope;
|
|
152
|
-
export function assertComposedScopeIntegrity(composed: ComposedScope): true;
|
|
153
|
-
/** Re-seals the existing canonical scope authority with effective-program lineage. */
|
|
154
|
-
export function bindEffectiveProgramAuthority(composed: ComposedScope, input: {
|
|
155
|
-
effectiveProgramDigest: string;
|
|
156
|
-
sourceRevisionSetDigest: string;
|
|
157
|
-
ancestorHardAuthorityDigest: string;
|
|
158
|
-
}): ComposedScope;
|
|
159
|
-
export interface ScopeCompositionRevalidation {
|
|
160
|
-
stale: boolean;
|
|
161
|
-
sourceRevisionSetChanged: boolean;
|
|
162
|
-
ancestorHardAuthorityChanged: boolean;
|
|
163
|
-
effectiveProgramChanged: boolean;
|
|
164
|
-
effectiveRevisionChanged: boolean;
|
|
165
|
-
conflictSetChanged: boolean;
|
|
166
|
-
compatible: boolean;
|
|
167
|
-
taintRequired: boolean;
|
|
168
|
-
}
|
|
169
|
-
/** Reference-equivalent dependency check for an already materialized scope. */
|
|
170
|
-
export function compositionDependencyStale(previous: ComposedScope, next: ComposedScope): boolean;
|
|
171
|
-
/** Revalidation must be explicit before a changed composition can be served. */
|
|
172
|
-
export function revalidateScopeComposition(previous: ComposedScope, next: ComposedScope): ScopeCompositionRevalidation;
|
|
173
|
-
export function composeScope(input: {
|
|
174
|
-
chain: readonly HierarchicalScope[];
|
|
175
|
-
delegation?: ScopeDelegation | null;
|
|
176
|
-
now?: string;
|
|
177
|
-
availablePermissions?: readonly string[];
|
|
178
|
-
effectiveRevision?: EffectiveRevisionBinding;
|
|
179
|
-
sourceRevisions?: readonly ScopeBehaviorRevision[];
|
|
180
|
-
}): ComposedScope;
|
|
181
|
-
/** Compose all supplied delegations, rejecting duplicate ids and preserving one digest for runtime checks. */
|
|
182
|
-
export function composeDelegatedScope(input: {
|
|
183
|
-
chain: readonly HierarchicalScope[];
|
|
184
|
-
delegations: readonly ScopeDelegation[];
|
|
185
|
-
now?: string;
|
|
186
|
-
availablePermissions?: readonly string[];
|
|
187
|
-
effectiveRevision?: EffectiveRevisionBinding;
|
|
188
|
-
sourceRevisions?: readonly ScopeBehaviorRevision[];
|
|
189
|
-
}): ComposedScope;
|
|
190
|
-
/** Reference-shaped exception delegation: parent-authored, exact-child and digest-bound. */
|
|
191
|
-
export function composeReferenceDelegatedScope(input: {
|
|
192
|
-
chain: readonly HierarchicalScope[];
|
|
193
|
-
delegation: ReferenceScopeDelegation;
|
|
194
|
-
now?: string;
|
|
195
|
-
availablePermissions?: readonly string[];
|
|
196
|
-
effectiveRevision?: EffectiveRevisionBinding;
|
|
197
|
-
sourceRevisions?: readonly ScopeBehaviorRevision[];
|
|
198
|
-
}): ComposedScope;
|
|
199
|
-
}
|
|
200
|
-
declare module "runtime/src/mcp-gateway" {
|
|
201
|
-
export const MCP_PROTOCOL_VERSIONS: readonly ["2026-07-28", "2025-11-25", "2025-03-26"];
|
|
202
|
-
export function negotiateMcpProtocolVersion(offered: unknown): string;
|
|
203
|
-
import { type ComposedScope } from "domain/src/scope-composer";
|
|
204
|
-
import type { Scope } from "domain/src/vnext";
|
|
205
|
-
export interface McpInvocation extends Scope {
|
|
206
|
-
id: string;
|
|
207
|
-
server: string;
|
|
208
|
-
tool: string;
|
|
209
|
-
arguments: Record<string, unknown>;
|
|
210
|
-
receiptId: string;
|
|
211
|
-
idempotencyKey: string;
|
|
212
|
-
authorityDigest?: string;
|
|
213
|
-
composedScope?: ComposedScope;
|
|
214
|
-
}
|
|
215
|
-
export interface McpResult extends Scope {
|
|
216
|
-
invocationId: string;
|
|
217
|
-
ok: boolean;
|
|
218
|
-
result?: unknown;
|
|
219
|
-
error?: string;
|
|
220
|
-
provenanceDigest: string;
|
|
221
|
-
server: string;
|
|
222
|
-
tool: string;
|
|
223
|
-
receiptId: string;
|
|
224
|
-
idempotencyKey: string;
|
|
225
|
-
argumentsDigest: string;
|
|
226
|
-
authorityDecisionDigest: string;
|
|
227
|
-
authorityDigest?: string | null;
|
|
228
|
-
}
|
|
229
|
-
export interface McpTransport {
|
|
230
|
-
call(input: {
|
|
231
|
-
server: string;
|
|
232
|
-
tool: string;
|
|
233
|
-
arguments: Record<string, unknown>;
|
|
234
|
-
signal?: AbortSignal;
|
|
235
|
-
}): Promise<{
|
|
236
|
-
result?: unknown;
|
|
237
|
-
error?: string;
|
|
238
|
-
}>;
|
|
239
|
-
}
|
|
240
|
-
export interface McpToolDefinition {
|
|
241
|
-
name: string;
|
|
242
|
-
description?: string;
|
|
243
|
-
inputSchema: Record<string, unknown>;
|
|
244
|
-
effectful?: boolean;
|
|
245
|
-
}
|
|
246
|
-
export interface McpResourceDefinition {
|
|
247
|
-
uri: string;
|
|
248
|
-
name: string;
|
|
249
|
-
description?: string;
|
|
250
|
-
mimeType?: string;
|
|
251
|
-
}
|
|
252
|
-
export interface McpPromptDefinition {
|
|
253
|
-
name: string;
|
|
254
|
-
description?: string;
|
|
255
|
-
arguments?: readonly Record<string, unknown>[];
|
|
256
|
-
}
|
|
257
|
-
export interface McpAuthorityDecision {
|
|
258
|
-
allowed: boolean;
|
|
259
|
-
decisionDigest: string;
|
|
260
|
-
reason?: string;
|
|
261
|
-
}
|
|
262
|
-
export interface McpCancellationRegistry {
|
|
263
|
-
register(requestId: string): AbortSignal;
|
|
264
|
-
cancel(requestId: string): boolean;
|
|
265
|
-
unregister(requestId: string, signal?: AbortSignal): void;
|
|
266
|
-
}
|
|
267
|
-
export function canonicalMcpJson(value: unknown): string;
|
|
268
|
-
export function verifyMcpResult(result: McpResult): true;
|
|
269
|
-
export function createMcpCancellationRegistry(): McpCancellationRegistry;
|
|
270
|
-
export function parseMcpEventStream(body: string, expectedId?: string): readonly string[];
|
|
271
|
-
export function createRegisteredMcpTransport(input: {
|
|
272
|
-
endpoint: string;
|
|
273
|
-
allowedHosts: readonly string[];
|
|
274
|
-
fetcher?: typeof fetch;
|
|
275
|
-
timeoutMs?: number;
|
|
276
|
-
protocolVersion?: string;
|
|
277
|
-
headers?: Readonly<Record<string, string>>;
|
|
278
|
-
}): McpTransport;
|
|
279
|
-
export function handleMcpJsonRpc(input: {
|
|
280
|
-
request: {
|
|
281
|
-
jsonrpc: '2.0';
|
|
282
|
-
id?: string | number;
|
|
283
|
-
method: string;
|
|
284
|
-
params?: Record<string, unknown>;
|
|
285
|
-
};
|
|
286
|
-
server: string;
|
|
287
|
-
tools: readonly McpToolDefinition[];
|
|
288
|
-
resources?: readonly McpResourceDefinition[];
|
|
289
|
-
prompts?: readonly McpPromptDefinition[];
|
|
290
|
-
readResource?: (uri: string) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
|
|
291
|
-
getPrompt?: (name: string, args: Record<string, unknown>) => Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
|
|
292
|
-
invocation: Omit<McpInvocation, 'server' | 'tool' | 'arguments'>;
|
|
293
|
-
transport: McpTransport;
|
|
294
|
-
signal?: AbortSignal;
|
|
295
|
-
cancellationRegistry?: McpCancellationRegistry;
|
|
296
|
-
authorize?: (input: {
|
|
297
|
-
invocation: McpInvocation;
|
|
298
|
-
definition: McpToolDefinition;
|
|
299
|
-
}) => Promise<McpAuthorityDecision> | McpAuthorityDecision;
|
|
300
|
-
}): Promise<Record<string, unknown> | null>;
|
|
301
|
-
export function invokeMcpTool(input: {
|
|
302
|
-
invocation: McpInvocation;
|
|
303
|
-
transport: McpTransport;
|
|
304
|
-
authority?: McpAuthorityDecision;
|
|
305
|
-
signal?: AbortSignal;
|
|
306
|
-
}): Promise<McpResult>;
|
|
307
|
-
}
|
|
308
|
-
declare module "mcp/src/index" {
|
|
309
|
-
export * from "runtime/src/mcp-gateway";
|
|
310
|
-
}
|
|
1
|
+
export {ViraClient} from "@tryvira/sdk";
|
|
2
|
+
export type {ViraClientOptions, ViraResponse} from "@tryvira/sdk";
|
package/dist/index.js
CHANGED
|
@@ -1,224 +1,5 @@
|
|
|
1
|
-
//
|
|
2
|
-
import {
|
|
3
|
-
import { isIP } from "node:net";
|
|
4
|
-
|
|
5
|
-
// ../domain/src/scope-composer.ts
|
|
6
|
-
import { createHash } from "node:crypto";
|
|
7
|
-
function canonical(value) {
|
|
8
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
9
|
-
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
10
|
-
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
11
|
-
}
|
|
12
|
-
var digest = (value) => createHash("sha256").update(canonical(value)).digest("hex");
|
|
13
|
-
function assertComposedScopeIntegrity(composed) {
|
|
14
|
-
const conflictSetDigest = digest(composed.conflicts);
|
|
15
|
-
if (conflictSetDigest !== composed.conflictSetDigest) throw new Error("SCOPE_CONFLICT_DIGEST_MISMATCH");
|
|
16
|
-
const compositionDigest = digest({ chain: composed.chain, permissions: composed.permissions, delegationIds: [...composed.delegationIds ?? []].sort(), conflictSetDigest, effectiveRevision: composed.effectiveRevision ?? null, sourceRevisionSetDigest: composed.sourceRevisionSetDigest ?? null, ancestorHardAuthorityDigest: composed.ancestorHardAuthorityDigest ?? null, effectiveProgramDigest: composed.effectiveProgramDigest ?? null });
|
|
17
|
-
if (compositionDigest !== composed.compositionDigest) throw new Error("SCOPE_COMPOSITION_DIGEST_MISMATCH");
|
|
18
|
-
return true;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// ../runtime/src/mcp-gateway.ts
|
|
22
|
-
var MCP_PROTOCOL_VERSIONS = ["2026-07-28", "2025-11-25", "2025-03-26"];
|
|
23
|
-
function negotiateMcpProtocolVersion(offered) {
|
|
24
|
-
const value = String(offered ?? "");
|
|
25
|
-
return MCP_PROTOCOL_VERSIONS.includes(value) ? value : "2025-03-26";
|
|
26
|
-
}
|
|
27
|
-
function assertPublicMcpHost(hostname) {
|
|
28
|
-
const host = hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
|
29
|
-
if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) throw new Error("MCP_UPSTREAM_PRIVATE_HOST");
|
|
30
|
-
const version = isIP(host);
|
|
31
|
-
if (version === 4) {
|
|
32
|
-
const octets = host.split(".").map(Number);
|
|
33
|
-
if (octets[0] === 10 || octets[0] === 127 || octets[0] === 0 || octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31 || octets[0] === 192 && octets[1] === 168 || octets[0] === 169 && octets[1] === 254) throw new Error("MCP_UPSTREAM_PRIVATE_HOST");
|
|
34
|
-
}
|
|
35
|
-
if (version === 6 && ["::1", "::", "fc", "fd", "fe8", "fe9", "fea", "feb"].some((prefix) => host === prefix || host.startsWith(`${prefix}:`))) throw new Error("MCP_UPSTREAM_PRIVATE_HOST");
|
|
36
|
-
}
|
|
37
|
-
function canonicalMcpJson(value) {
|
|
38
|
-
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
39
|
-
if (Array.isArray(value)) return `[${value.map(canonicalMcpJson).join(",")}]`;
|
|
40
|
-
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonicalMcpJson(value[key])}`).join(",")}}`;
|
|
41
|
-
}
|
|
42
|
-
function verifyMcpResult(result) {
|
|
43
|
-
const { provenanceDigest, ...body } = result;
|
|
44
|
-
const expected = createHash2("sha256").update(canonicalMcpJson(body)).digest("hex");
|
|
45
|
-
if (provenanceDigest !== expected) throw new Error("MCP_PROVENANCE_DIGEST_INVALID");
|
|
46
|
-
return true;
|
|
47
|
-
}
|
|
48
|
-
function createMcpCancellationRegistry() {
|
|
49
|
-
const controllers = /* @__PURE__ */ new Map();
|
|
50
|
-
return { register(requestId) {
|
|
51
|
-
if (!requestId.trim()) throw new Error("MCP_REQUEST_ID_REQUIRED");
|
|
52
|
-
const previous = controllers.get(requestId);
|
|
53
|
-
previous?.abort();
|
|
54
|
-
const controller = new AbortController();
|
|
55
|
-
controllers.set(requestId, controller);
|
|
56
|
-
return controller.signal;
|
|
57
|
-
}, cancel(requestId) {
|
|
58
|
-
const controller = controllers.get(requestId);
|
|
59
|
-
if (!controller) return false;
|
|
60
|
-
controller.abort();
|
|
61
|
-
return true;
|
|
62
|
-
}, unregister(requestId, signal) {
|
|
63
|
-
const controller = controllers.get(requestId);
|
|
64
|
-
if (controller && (!signal || controller.signal === signal)) controllers.delete(requestId);
|
|
65
|
-
} };
|
|
66
|
-
}
|
|
67
|
-
function combineMcpAbortSignals(...signals) {
|
|
68
|
-
const active = signals.filter((signal) => Boolean(signal));
|
|
69
|
-
if (active.length === 0) return void 0;
|
|
70
|
-
if (active.length === 1) return active[0];
|
|
71
|
-
const controller = new AbortController();
|
|
72
|
-
const abort = () => controller.abort();
|
|
73
|
-
for (const signal of active) {
|
|
74
|
-
if (signal.aborted) {
|
|
75
|
-
controller.abort();
|
|
76
|
-
break;
|
|
77
|
-
}
|
|
78
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
79
|
-
}
|
|
80
|
-
return controller.signal;
|
|
81
|
-
}
|
|
82
|
-
function parseMcpEventStream(body, expectedId) {
|
|
83
|
-
const payloads = [];
|
|
84
|
-
for (const event of body.split(/\r?\n\r?\n/)) {
|
|
85
|
-
const data = [];
|
|
86
|
-
for (const line of event.split(/\r?\n/)) {
|
|
87
|
-
if (!line || line.startsWith(":")) continue;
|
|
88
|
-
const separator = line.indexOf(":");
|
|
89
|
-
const field = separator < 0 ? line : line.slice(0, separator);
|
|
90
|
-
if (field !== "data") continue;
|
|
91
|
-
const value = line.slice(separator + 1).startsWith(" ") ? line.slice(separator + 2) : line.slice(separator + 1);
|
|
92
|
-
data.push(value);
|
|
93
|
-
}
|
|
94
|
-
if (data.length) payloads.push(data.join("\n"));
|
|
95
|
-
}
|
|
96
|
-
return payloads;
|
|
97
|
-
}
|
|
98
|
-
async function readMcpResponseBody(response) {
|
|
99
|
-
if (!response.body) return response.text();
|
|
100
|
-
const reader = response.body.getReader();
|
|
101
|
-
const decoder = new TextDecoder();
|
|
102
|
-
let body = "";
|
|
103
|
-
try {
|
|
104
|
-
for (; ; ) {
|
|
105
|
-
const chunk = await reader.read();
|
|
106
|
-
body += decoder.decode(chunk.value ?? new Uint8Array(), { stream: !chunk.done });
|
|
107
|
-
if (chunk.done) return body;
|
|
108
|
-
}
|
|
109
|
-
} finally {
|
|
110
|
-
reader.releaseLock();
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function parseMcpResponseBody(body, contentType, expectedId) {
|
|
114
|
-
const payloads = contentType.toLowerCase().includes("text/event-stream") ? parseMcpEventStream(body, expectedId) : [body];
|
|
115
|
-
let last;
|
|
116
|
-
for (const payload of payloads) {
|
|
117
|
-
try {
|
|
118
|
-
const parsed = JSON.parse(payload);
|
|
119
|
-
last = parsed;
|
|
120
|
-
} catch {
|
|
121
|
-
continue;
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
if (!last) return { error: "MCP_UPSTREAM_RESPONSE_INVALID" };
|
|
125
|
-
if (last.id !== void 0 && String(last.id) !== expectedId) return { error: "MCP_UPSTREAM_RESPONSE_ID_MISMATCH" };
|
|
126
|
-
return last.error ? { error: last.error.message ?? "MCP_UPSTREAM_ERROR" } : { result: last.result };
|
|
127
|
-
}
|
|
128
|
-
function createRegisteredMcpTransport(input) {
|
|
129
|
-
const url = new URL(input.endpoint);
|
|
130
|
-
if (url.protocol !== "https:") throw new Error("MCP_UPSTREAM_HTTPS_REQUIRED");
|
|
131
|
-
assertPublicMcpHost(url.hostname);
|
|
132
|
-
if (!input.allowedHosts.includes(url.host)) throw new Error("MCP_UPSTREAM_HOST_NOT_ALLOWED");
|
|
133
|
-
const fetcher = input.fetcher ?? fetch;
|
|
134
|
-
const timeoutMs = input.timeoutMs ?? 1e4;
|
|
135
|
-
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e4) throw new Error("MCP_UPSTREAM_TIMEOUT_INVALID");
|
|
136
|
-
const protocolVersion = input.protocolVersion ?? "2025-03-26";
|
|
137
|
-
return { call: async ({ server, tool, arguments: args, signal }) => {
|
|
138
|
-
const controller = new AbortController();
|
|
139
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
140
|
-
const abort = () => controller.abort();
|
|
141
|
-
if (signal?.aborted) controller.abort();
|
|
142
|
-
else signal?.addEventListener("abort", abort, { once: true });
|
|
143
|
-
try {
|
|
144
|
-
const response = await fetcher(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": protocolVersion, ...input.headers }, signal: controller.signal, body: JSON.stringify({ jsonrpc: "2.0", id: `${server}:${tool}`, method: "tools/call", params: { name: tool, arguments: args } }) });
|
|
145
|
-
if (!response.ok) return { error: `MCP_UPSTREAM_HTTP_${response.status}` };
|
|
146
|
-
return parseMcpResponseBody(await readMcpResponseBody(response), response.headers.get("content-type") ?? "application/json", `${server}:${tool}`);
|
|
147
|
-
} catch (error) {
|
|
148
|
-
return { error: error instanceof Error && error.name === "AbortError" ? signal?.aborted ? "MCP_REQUEST_CANCELLED" : "MCP_UPSTREAM_TIMEOUT" : "MCP_UPSTREAM_TRANSPORT_ERROR" };
|
|
149
|
-
} finally {
|
|
150
|
-
clearTimeout(timer);
|
|
151
|
-
signal?.removeEventListener("abort", abort);
|
|
152
|
-
}
|
|
153
|
-
} };
|
|
154
|
-
}
|
|
155
|
-
async function handleMcpJsonRpc(input) {
|
|
156
|
-
const { request, server, tools, transport } = input;
|
|
157
|
-
if (request.jsonrpc !== "2.0" || !request.method) throw new Error("MCP_JSONRPC_INVALID");
|
|
158
|
-
if (request.method === "initialize") return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, result: { protocolVersion: "2025-03-26", serverInfo: { name: server, version: "1" }, capabilities: { tools: {}, resources: input.resources ? {} : void 0, prompts: input.prompts ? {} : void 0 } } };
|
|
159
|
-
if (request.method === "notifications/initialized") return null;
|
|
160
|
-
if (request.method === "notifications/cancelled") {
|
|
161
|
-
const requestId2 = String(request.params?.requestId ?? "");
|
|
162
|
-
input.cancellationRegistry?.cancel(requestId2);
|
|
163
|
-
return null;
|
|
164
|
-
}
|
|
165
|
-
if (request.method === "tools/list") return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, result: { tools } };
|
|
166
|
-
if (request.method === "resources/list") return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, result: { resources: input.resources ?? [] } };
|
|
167
|
-
if (request.method === "prompts/list") return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, result: { prompts: input.prompts ?? [] } };
|
|
168
|
-
if (request.method === "resources/read") {
|
|
169
|
-
const value = input.readResource ? await input.readResource(String(request.params?.uri ?? "")) : null;
|
|
170
|
-
return request.id === void 0 ? null : value ? { jsonrpc: "2.0", id: request.id, result: value } : { jsonrpc: "2.0", id: request.id, error: { code: -32602, message: "RESOURCE_NOT_FOUND" } };
|
|
171
|
-
}
|
|
172
|
-
if (request.method === "prompts/get") {
|
|
173
|
-
const value = input.getPrompt ? await input.getPrompt(String(request.params?.name ?? ""), request.params?.arguments ?? {}) : null;
|
|
174
|
-
return request.id === void 0 ? null : value ? { jsonrpc: "2.0", id: request.id, result: value } : { jsonrpc: "2.0", id: request.id, error: { code: -32602, message: "PROMPT_NOT_FOUND" } };
|
|
175
|
-
}
|
|
176
|
-
if (request.method !== "tools/call") return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, error: { code: -32601, message: "METHOD_NOT_FOUND" } };
|
|
177
|
-
const tool = String(request.params?.name ?? "");
|
|
178
|
-
const definition = tools.find((item) => item.name === tool);
|
|
179
|
-
if (!definition) return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, error: { code: -32602, message: "TOOL_NOT_FOUND" } };
|
|
180
|
-
const invocation = { ...input.invocation, server, tool, arguments: request.params?.arguments ?? {} };
|
|
181
|
-
const authority = definition.effectful ? input.authorize ? await input.authorize({ invocation, definition }) : { allowed: false, decisionDigest: "", reason: "MCP_AUTHORITY_REQUIRED" } : { allowed: true, decisionDigest: "read-only" };
|
|
182
|
-
if (!authority.allowed) return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, error: { code: -32003, message: authority.reason ?? "MCP_AUTHORITY_DENIED", data: { decisionDigest: authority.decisionDigest } } };
|
|
183
|
-
const requestId = String(request.id ?? "");
|
|
184
|
-
const requestSignal = input.cancellationRegistry && requestId ? input.cancellationRegistry.register(requestId) : void 0;
|
|
185
|
-
try {
|
|
186
|
-
const result = await invokeMcpTool({ invocation, transport, authority, signal: combineMcpAbortSignals(input.signal, requestSignal) });
|
|
187
|
-
return request.id === void 0 ? null : { jsonrpc: "2.0", id: request.id, result: { content: [{ type: "text", text: JSON.stringify(result.result ?? result.error ?? null) }], isError: !result.ok, provenanceDigest: result.provenanceDigest } };
|
|
188
|
-
} finally {
|
|
189
|
-
if (requestSignal) input.cancellationRegistry?.unregister(requestId, requestSignal);
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
async function invokeMcpTool(input) {
|
|
193
|
-
const { invocation, transport } = input;
|
|
194
|
-
if (!invocation.id || !invocation.server || !invocation.tool || !invocation.receiptId || !invocation.idempotencyKey) throw new Error("MCP_INVOCATION_FIELDS_REQUIRED");
|
|
195
|
-
if (invocation.authorityDigest !== void 0 && !/^[a-f0-9]{64}$/.test(invocation.authorityDigest)) throw new Error("MCP_AUTHORITY_DIGEST_INVALID");
|
|
196
|
-
if (invocation.composedScope) {
|
|
197
|
-
assertComposedScopeIntegrity(invocation.composedScope);
|
|
198
|
-
if (invocation.authorityDigest !== void 0 && invocation.authorityDigest !== invocation.composedScope.compositionDigest) throw new Error("MCP_AUTHORITY_MISMATCH");
|
|
199
|
-
if (!invocation.composedScope.serveable) throw new Error("MCP_SCOPE_COMPOSITION_CONFLICT");
|
|
200
|
-
}
|
|
201
|
-
if (input.authority && !input.authority.allowed) throw new Error("MCP_AUTHORITY_DENIED");
|
|
202
|
-
if (!transport || typeof transport.call !== "function") throw new Error("MCP_TRANSPORT_REQUIRED");
|
|
203
|
-
let response;
|
|
204
|
-
try {
|
|
205
|
-
response = await transport.call({ server: invocation.server, tool: invocation.tool, arguments: structuredClone(invocation.arguments), signal: input.signal });
|
|
206
|
-
} catch {
|
|
207
|
-
if (input.signal?.aborted) throw new Error("MCP_INVOCATION_CANCELLED");
|
|
208
|
-
response = { error: "MCP_TRANSPORT_ERROR" };
|
|
209
|
-
}
|
|
210
|
-
const argumentsDigest = createHash2("sha256").update(canonicalMcpJson(invocation.arguments)).digest("hex");
|
|
211
|
-
const body = { invocationId: invocation.id, organizationId: invocation.organizationId, projectId: invocation.projectId, environmentId: invocation.environmentId, server: invocation.server, tool: invocation.tool, receiptId: invocation.receiptId, idempotencyKey: invocation.idempotencyKey, argumentsDigest, authorityDecisionDigest: input.authority?.decisionDigest ?? "not-required", authorityDigest: invocation.authorityDigest ?? null, ok: !response.error, result: response.result, error: response.error };
|
|
212
|
-
return Object.freeze({ ...body, provenanceDigest: createHash2("sha256").update(canonicalMcpJson(body)).digest("hex") });
|
|
213
|
-
}
|
|
1
|
+
// packages/mcp/src/index.ts
|
|
2
|
+
import { ViraClient } from "@tryvira/sdk";
|
|
214
3
|
export {
|
|
215
|
-
|
|
216
|
-
canonicalMcpJson,
|
|
217
|
-
createMcpCancellationRegistry,
|
|
218
|
-
createRegisteredMcpTransport,
|
|
219
|
-
handleMcpJsonRpc,
|
|
220
|
-
invokeMcpTool,
|
|
221
|
-
negotiateMcpProtocolVersion,
|
|
222
|
-
parseMcpEventStream,
|
|
223
|
-
verifyMcpResult
|
|
4
|
+
ViraClient
|
|
224
5
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tryvira/mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.42",
|
|
4
4
|
"description": "Vira MCP client and npx-ready JSON-RPC launcher.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"vira",
|
|
@@ -31,14 +31,13 @@
|
|
|
31
31
|
"bin": {
|
|
32
32
|
"vira-mcp": "dist/cli.js"
|
|
33
33
|
},
|
|
34
|
-
"files": ["dist/index.js", "dist/index.d.ts", "dist/cli.js", "
|
|
34
|
+
"files": ["dist/index.js", "dist/index.d.ts", "dist/cli.js", "README.md"],
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"access": "public"
|
|
37
37
|
},
|
|
38
38
|
"dependencies": {
|
|
39
39
|
"@modelcontextprotocol/server": "^2.4.0",
|
|
40
|
-
"
|
|
41
|
-
"sql.js": "^1.14.2",
|
|
40
|
+
"@tryvira/sdk": "^0.1.42",
|
|
42
41
|
"zod": "^4.2.0"
|
|
43
42
|
},
|
|
44
43
|
"scripts": {
|