@cratis/pi 7.162.0 → 7.164.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/package/corpus/harnesses/pi/extensions/cratis-mcp/CorpusServer.ts +2 -0
- package/package/corpus/harnesses/pi/extensions/cratis-mcp/ServerBridge.ts +45 -12
- package/package/corpus/harnesses/pi/extensions/cratis-mcp/activation.ts +74 -0
- package/package/corpus/harnesses/pi/extensions/cratis-mcp/configuration.ts +10 -0
- package/package/corpus/harnesses/pi/extensions/cratis-mcp/index.ts +144 -80
- package/package/corpus/harnesses/pi/extensions/cratis-mcp/servers.ts +19 -12
- package/package/corpus/skills/cratis-chronicle-cli-operations/references/project-tooling.md +4 -2
- package/package/corpus/skills/cratis-screenplay-model-authoring/SKILL.md +6 -0
- package/package.json +1 -1
|
@@ -7,6 +7,8 @@ export interface CorpusServer {
|
|
|
7
7
|
command: string;
|
|
8
8
|
args: string[];
|
|
9
9
|
env: Record<string, string>;
|
|
10
|
+
/** `mcpServers.<id>.eager`: register the tools at session start instead of on demand through `cratis_enable_mcp`. */
|
|
11
|
+
eager: boolean;
|
|
10
12
|
}
|
|
11
13
|
|
|
12
14
|
/** The servers to start for a project plus the explicit messages for everything skipped. */
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
3
|
|
|
4
4
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
import { createActivation, enabledText, type Activation, type Enabler } from './activation.ts';
|
|
5
6
|
import { object } from './configuration.ts';
|
|
6
7
|
import type { CorpusServer } from './CorpusServer.ts';
|
|
7
8
|
import { startServer } from './process.ts';
|
|
@@ -25,10 +26,12 @@ export interface ServerBridge {
|
|
|
25
26
|
dispose(): void;
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (project: string, server: CorpusServer) => StdioConnection = startServer, deadlineMilliseconds = 15_000): ServerBridge {
|
|
29
|
+
export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (project: string, server: CorpusServer) => StdioConnection = startServer, deadlineMilliseconds = 15_000, activation: Activation = createActivation(pi)): ServerBridge {
|
|
29
30
|
const connections = new Map<string, StdioConnection>();
|
|
31
|
+
const toolsByServer = new Map<string, string[]>();
|
|
30
32
|
const registered = new Set<string>();
|
|
31
33
|
const paused = new Set<string>();
|
|
34
|
+
const owner = 'servers';
|
|
32
35
|
let selectionKey: string | undefined;
|
|
33
36
|
|
|
34
37
|
const notify = (context: ExtensionContext, messages: string[]): void => {
|
|
@@ -42,6 +45,7 @@ export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (p
|
|
|
42
45
|
const dispose = (): void => {
|
|
43
46
|
connections.forEach(connection => connection.dispose());
|
|
44
47
|
connections.clear();
|
|
48
|
+
toolsByServer.clear();
|
|
45
49
|
deactivate();
|
|
46
50
|
};
|
|
47
51
|
interface Started { server: CorpusServer; connection?: StdioConnection; catalog?: ServerCatalog; messages: string[] }
|
|
@@ -60,8 +64,10 @@ export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (p
|
|
|
60
64
|
return { server, connection, messages: [`MCP server '${server.id}' is unavailable: ${error instanceof Error ? error.message : String(error)}`] };
|
|
61
65
|
}
|
|
62
66
|
};
|
|
63
|
-
|
|
64
|
-
|
|
67
|
+
/** Registers the server's tools and returns the native names it won; conflicts are reported in `messages`. */
|
|
68
|
+
const register = ({ server, connection, catalog, messages }: Started, claimed: Set<string>): string[] => {
|
|
69
|
+
if (!connection) return [];
|
|
70
|
+
const added: string[] = [];
|
|
65
71
|
const existing = new Set(pi.getAllTools().map(tool => tool.name));
|
|
66
72
|
for (const tool of catalog?.tools ?? []) {
|
|
67
73
|
if (claimed.has(tool.nativeName) || (existing.has(tool.nativeName) && !registered.has(tool.nativeName))) {
|
|
@@ -69,6 +75,7 @@ export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (p
|
|
|
69
75
|
continue;
|
|
70
76
|
}
|
|
71
77
|
claimed.add(tool.nativeName);
|
|
78
|
+
added.push(tool.nativeName);
|
|
72
79
|
pi.registerTool({
|
|
73
80
|
name: tool.nativeName,
|
|
74
81
|
label: `${server.id} ${tool.name}`,
|
|
@@ -86,11 +93,37 @@ export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (p
|
|
|
86
93
|
},
|
|
87
94
|
});
|
|
88
95
|
}
|
|
96
|
+
toolsByServer.set(server.id, added);
|
|
97
|
+
return added;
|
|
98
|
+
};
|
|
99
|
+
/** Never re-enable a user-disabled tool. SDK allow/exclude restrictions still filter registration. */
|
|
100
|
+
const restoreActive = (added: Iterable<string>, oldNames: Set<string>, previouslyActive: Set<string>): void => {
|
|
101
|
+
const fresh = new Set(added);
|
|
102
|
+
const next = pi.getActiveTools().filter(name => !fresh.has(name) || !oldNames.has(name) || previouslyActive.has(name));
|
|
103
|
+
for (const name of fresh) if (oldNames.has(name) && previouslyActive.has(name)) next.push(name);
|
|
104
|
+
pi.setActiveTools([...new Set(next)]);
|
|
105
|
+
};
|
|
106
|
+
/** On-demand start of one deferred server; the other servers' connections and tools are untouched. */
|
|
107
|
+
const enable = async (context: ExtensionContext, server: CorpusServer): Promise<string> => {
|
|
108
|
+
const label = `MCP server '${server.id}'`;
|
|
109
|
+
const current = connections.get(server.id);
|
|
110
|
+
if (current && !current.stopped) return enabledText(label, toolsByServer.get(server.id) ?? [], true);
|
|
111
|
+
current?.dispose();
|
|
112
|
+
connections.delete(server.id);
|
|
113
|
+
const previouslyActive = new Set([...pi.getActiveTools(), ...paused]);
|
|
114
|
+
const oldNames = new Set(registered);
|
|
115
|
+
const outcome = await start(context, server);
|
|
116
|
+
if (!outcome.catalog) throw new Error(outcome.messages.join(' '));
|
|
117
|
+
const claimed = new Set([...toolsByServer].filter(([id]) => id !== server.id).flatMap(([, names]) => names));
|
|
118
|
+
const added = register(outcome, claimed);
|
|
119
|
+
added.forEach(name => { registered.add(name); paused.delete(name); });
|
|
120
|
+
restoreActive(added, oldNames, previouslyActive);
|
|
121
|
+
return [enabledText(label, added, false), ...outcome.messages].join('\n');
|
|
89
122
|
};
|
|
90
123
|
const refresh = async (context: ExtensionContext, newSession: boolean): Promise<void> => {
|
|
91
124
|
let selection: ReturnType<typeof selectedCorpusServers>;
|
|
92
125
|
try { selection = selectedCorpusServers(context.cwd, corpus); }
|
|
93
|
-
catch (error) { dispose(); selectionKey = undefined; throw error; }
|
|
126
|
+
catch (error) { dispose(); selectionKey = undefined; activation.publish(owner, new Map()); throw error; }
|
|
94
127
|
const key = JSON.stringify(selection);
|
|
95
128
|
if (!newSession && key === selectionKey) return;
|
|
96
129
|
const previouslyActive = new Set([...pi.getActiveTools(), ...paused]);
|
|
@@ -99,17 +132,17 @@ export function createServerBridge(pi: ExtensionAPI, corpus: string, connect: (p
|
|
|
99
132
|
selectionKey = key;
|
|
100
133
|
const messages = [...selection.messages];
|
|
101
134
|
const claimed = new Set<string>();
|
|
102
|
-
//
|
|
103
|
-
|
|
135
|
+
// Deferred servers only publish an enabler; nothing starts or registers until `cratis_enable_mcp` asks for it.
|
|
136
|
+
activation.publish(owner, new Map(selection.servers.filter(server => !server.eager).map(server => [server.id, (enableContext: ExtensionContext) => enable(enableContext, server)] satisfies [string, Enabler])));
|
|
137
|
+
// Eager servers start in parallel; a slow or hung one is abandoned at its own deadline and never delays the others.
|
|
138
|
+
const outcomes = await Promise.all(selection.servers.filter(server => server.eager).map(server => start(context, server)));
|
|
104
139
|
for (const outcome of outcomes) { register(outcome, claimed); messages.push(...outcome.messages); }
|
|
105
140
|
claimed.forEach(name => registered.add(name));
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
pi.setActiveTools([...new Set(next)]);
|
|
110
|
-
paused.clear();
|
|
141
|
+
restoreActive(claimed, oldNames, previouslyActive);
|
|
142
|
+
// Only names restored above leave `paused`; deferred servers keep theirs until `enable` reactivates them.
|
|
143
|
+
claimed.forEach(name => paused.delete(name));
|
|
111
144
|
notify(context, messages);
|
|
112
145
|
};
|
|
113
146
|
|
|
114
|
-
return { refresh, dispose: () => { dispose(); selectionKey = undefined; } };
|
|
147
|
+
return { refresh, dispose: () => { dispose(); selectionKey = undefined; activation.publish(owner, new Map()); } };
|
|
115
148
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Copyright (c) Cratis. All rights reserved.
|
|
2
|
+
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
3
|
+
|
|
4
|
+
import type { ExtensionAPI, ExtensionContext, ToolDefinition } from '@earendil-works/pi-coding-agent';
|
|
5
|
+
|
|
6
|
+
/** Starts one deferred server (connect, discover, register) and returns the text the model sees. Must be idempotent once started. */
|
|
7
|
+
export type Enabler = (context: ExtensionContext) => Promise<string>;
|
|
8
|
+
|
|
9
|
+
export const enableToolName = 'cratis_enable_mcp';
|
|
10
|
+
|
|
11
|
+
/** The text every enabler returns on success: the tools only become callable on the next LLM step. */
|
|
12
|
+
export function enabledText(label: string, names: string[], alreadyEnabled: boolean): string {
|
|
13
|
+
const list = names.length ? names.join(', ') : 'none';
|
|
14
|
+
return alreadyEnabled
|
|
15
|
+
? `${label} is already enabled. Its tools: ${list}.`
|
|
16
|
+
: `${label} is enabled. Its tools are available from the next step (not in this step's parallel tool calls): ${list}.`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Shared lifecycle for deferred MCP servers: each bridge publishes the servers it left unstarted, and one
|
|
21
|
+
* `cratis_enable_mcp` tool starts any of them on demand. Concurrent enables of the same server share one start.
|
|
22
|
+
*/
|
|
23
|
+
export interface Activation {
|
|
24
|
+
/** Replace every deferred server owned by `owner`; an empty map withdraws them. */
|
|
25
|
+
publish(owner: string, enablers: Map<string, Enabler>): void;
|
|
26
|
+
enable(id: string, context: ExtensionContext): Promise<string>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function createActivation(pi: ExtensionAPI): Activation {
|
|
30
|
+
const owners = new Map<string, Map<string, Enabler>>();
|
|
31
|
+
const inFlight = new Map<string, Promise<string>>();
|
|
32
|
+
let registeredIds = '';
|
|
33
|
+
|
|
34
|
+
const deferredIds = (): string[] => [...owners.values()].flatMap(enablers => [...enablers.keys()]);
|
|
35
|
+
const find = (id: string): Enabler | undefined => [...owners.values()].map(enablers => enablers.get(id)).find(enabler => enabler !== undefined);
|
|
36
|
+
|
|
37
|
+
const enable = (id: string, context: ExtensionContext): Promise<string> => {
|
|
38
|
+
const running = inFlight.get(id);
|
|
39
|
+
if (running) return running;
|
|
40
|
+
const enabler = find(id);
|
|
41
|
+
if (!enabler) return Promise.reject(new Error(`MCP server '${id}' is not deferred in this session. Deferred servers: ${deferredIds().join(', ') || 'none'}.`));
|
|
42
|
+
const started = enabler(context).finally(() => inFlight.delete(id));
|
|
43
|
+
inFlight.set(id, started);
|
|
44
|
+
return started;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const register = (): void => {
|
|
48
|
+
const ids = deferredIds();
|
|
49
|
+
const key = ids.join('\0');
|
|
50
|
+
if (!ids.length || key === registeredIds) return;
|
|
51
|
+
registeredIds = key;
|
|
52
|
+
pi.registerTool({
|
|
53
|
+
name: enableToolName,
|
|
54
|
+
label: 'Enable MCP server',
|
|
55
|
+
description: `Start a deferred MCP server and make its tools available. Deferred servers: ${ids.join(', ')}. Call this before using any of that server's tools; they appear from the next step.`,
|
|
56
|
+
parameters: { type: 'object', properties: { server: { type: 'string', enum: ids } }, required: ['server'], additionalProperties: false } as unknown as ToolDefinition['parameters'],
|
|
57
|
+
executionMode: 'sequential',
|
|
58
|
+
async execute(_toolCallId, parameters, _signal, _onUpdate, context) {
|
|
59
|
+
const server = (parameters as { server?: unknown }).server;
|
|
60
|
+
if (typeof server !== 'string') throw new Error('The server argument must be a string.');
|
|
61
|
+
const text = await enable(server, context);
|
|
62
|
+
return { content: [{ type: 'text', text }], details: { server } };
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
return {
|
|
68
|
+
enable,
|
|
69
|
+
publish(owner, enablers) {
|
|
70
|
+
if (enablers.size) owners.set(owner, enablers); else owners.delete(owner);
|
|
71
|
+
register();
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
5
5
|
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
6
|
|
|
7
|
+
/** `mcpServers.screenplay.eager`: absent is false; a non-boolean is a configuration error. */
|
|
8
|
+
function readEager(screenplay: unknown): boolean {
|
|
9
|
+
const eager = object(screenplay) ? screenplay.eager : undefined;
|
|
10
|
+
if (eager !== undefined && typeof eager !== 'boolean') throw new Error('Screenplay MCP eager must be a boolean.');
|
|
11
|
+
return eager === true;
|
|
12
|
+
}
|
|
13
|
+
|
|
7
14
|
export function object(value: unknown): value is Record<string, unknown> {
|
|
8
15
|
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
16
|
}
|
|
@@ -112,6 +119,8 @@ export function selectedServer(project: string, corpus: string) {
|
|
|
112
119
|
if (screenplay !== undefined && !object(screenplay)) throw new Error('Invalid Screenplay MCP configuration.');
|
|
113
120
|
if (object(screenplay) && screenplay.enabled === false) return undefined;
|
|
114
121
|
if (object(screenplay) && screenplay.enabled !== undefined && screenplay.enabled !== true) throw new Error('Screenplay MCP enabled must be a boolean.');
|
|
122
|
+
// Deferred by default: `eager: true` registers the tools at session start instead of on demand.
|
|
123
|
+
const eager = readEager(screenplay);
|
|
115
124
|
const descriptor = readJson(join(corpus, 'mcp-servers.json'));
|
|
116
125
|
// Any 1.x descriptor is accepted; another major loads no corpus MCP servers (the generic bridge reports it once).
|
|
117
126
|
if (!supportedSchema(descriptor.schemaVersion)) return undefined;
|
|
@@ -131,5 +140,6 @@ export function selectedServer(project: string, corpus: string) {
|
|
|
131
140
|
project: physicalProject,
|
|
132
141
|
root: root === undefined ? undefined : physicalRoot(physicalProject, root),
|
|
133
142
|
composedOnly: !nonApplicationSelection && root === undefined,
|
|
143
|
+
eager,
|
|
134
144
|
};
|
|
135
145
|
}
|
|
@@ -5,6 +5,7 @@ import { existsSync } from 'node:fs';
|
|
|
5
5
|
import { dirname, join, resolve } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
8
|
+
import { createActivation, enabledText } from './activation.ts';
|
|
8
9
|
import { ConnectionFailure } from './ConnectionFailure.ts';
|
|
9
10
|
import { object, selectedServer } from './configuration.ts';
|
|
10
11
|
import type { CorpusServer } from './CorpusServer.ts';
|
|
@@ -14,12 +15,19 @@ import { createServerBridge } from './ServerBridge.ts';
|
|
|
14
15
|
import type { DiscoveredTool } from './DiscoveredTool.ts';
|
|
15
16
|
import type { StdioConnection } from './StdioConnection.ts';
|
|
16
17
|
|
|
18
|
+
type Selection = NonNullable<ReturnType<typeof selectedServer>>;
|
|
19
|
+
|
|
20
|
+
/** One discovered tool bound to the connection it was discovered on. */
|
|
21
|
+
interface NativeCall { tool: DiscoveredTool; activeConnection: StdioConnection; modelRoot: string }
|
|
22
|
+
|
|
17
23
|
const extensionDirectory = dirname(fileURLToPath(import.meta.url));
|
|
18
24
|
const bundledCorpus = resolve(extensionDirectory, '..', '..', '..', '..');
|
|
19
25
|
|
|
20
26
|
/** Native tools go through Pi's tool_call restrictions and normal execution/result pipeline. */
|
|
21
27
|
export function registerBridge(pi: ExtensionAPI, corpus: string, connect = startConnection, checkVersion = supportsNoModelStartup, connectServer: (project: string, server: CorpusServer) => StdioConnection = startServer): void {
|
|
22
|
-
const
|
|
28
|
+
const activation = createActivation(pi);
|
|
29
|
+
const servers = createServerBridge(pi, corpus, connectServer, undefined, activation);
|
|
30
|
+
const owner = 'screenplay';
|
|
23
31
|
let connection: StdioConnection | undefined;
|
|
24
32
|
let selectionKey: string | undefined;
|
|
25
33
|
let attempted = false;
|
|
@@ -52,102 +60,158 @@ export function registerBridge(pi: ExtensionAPI, corpus: string, connect = start
|
|
|
52
60
|
}
|
|
53
61
|
if (!connection || connection.stopped) throw new Error('Screenplay connection is unavailable. No request was retried; explicitly reload after inspecting any uncertain mutation.');
|
|
54
62
|
};
|
|
63
|
+
const activeNames = (): string[] => pi.getActiveTools().filter(name => registered.has(name));
|
|
64
|
+
const isLiveFor = (key: string): boolean => connection !== undefined && !connection.stopped && key === selectionKey;
|
|
65
|
+
const assertCertain = (): void => {
|
|
66
|
+
if (uncertain) throw new Error('Screenplay mutation outcome remains unknown. Explicitly reload, inspect workspace-state, and obtain authorization before any recovery.');
|
|
67
|
+
};
|
|
55
68
|
const refresh = async (context: ExtensionContext, newSession = false): Promise<void> => {
|
|
56
69
|
if (newSession) { startupSupported = undefined; unavailableReported = false; }
|
|
57
70
|
const previouslyActive = new Set([...pi.getActiveTools(), ...paused]);
|
|
58
71
|
let selection: ReturnType<typeof selectedServer>;
|
|
59
72
|
try { selection = currentSelection(context); }
|
|
60
|
-
catch (error) { dispose(); throw error; }
|
|
73
|
+
catch (error) { dispose(); activation.publish(owner, new Map()); throw error; }
|
|
61
74
|
const key = JSON.stringify(selection);
|
|
62
75
|
if (!newSession && attempted && key === selectionKey) return;
|
|
63
76
|
dispose();
|
|
64
77
|
attempted = true;
|
|
65
78
|
selectionKey = key;
|
|
66
79
|
failures.clear();
|
|
80
|
+
activation.publish(owner, new Map());
|
|
67
81
|
if (!selection) return;
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
82
|
+
assertCertain();
|
|
83
|
+
// Deferred by default: the tools are discovered and registered only when the model calls cratis_enable_mcp.
|
|
84
|
+
if (!selection.eager) { activation.publish(owner, new Map([['screenplay', enable]])); return; }
|
|
85
|
+
await activate(context, selection, previouslyActive, false);
|
|
86
|
+
};
|
|
87
|
+
/** On-demand start. Starts over when the selection changed since the last refresh; an unavailable CLI is an error here, not a notice. */
|
|
88
|
+
const enable = async (context: ExtensionContext): Promise<string> => {
|
|
89
|
+
let selection: ReturnType<typeof selectedServer>;
|
|
90
|
+
try { selection = currentSelection(context); }
|
|
91
|
+
catch (error) { dispose(); throw error; }
|
|
92
|
+
if (!selection) throw new Error('Screenplay MCP is not selected for this project.');
|
|
93
|
+
const key = JSON.stringify(selection);
|
|
94
|
+
if (isLiveFor(key)) return enabledText('Screenplay MCP', activeNames(), true);
|
|
95
|
+
assertCertain();
|
|
96
|
+
const previouslyActive = new Set([...pi.getActiveTools(), ...paused]);
|
|
97
|
+
dispose();
|
|
98
|
+
attempted = true;
|
|
99
|
+
selectionKey = key;
|
|
100
|
+
failures.clear();
|
|
101
|
+
await activate(context, selection, previouslyActive, true);
|
|
102
|
+
return enabledText('Screenplay MCP', activeNames(), false);
|
|
103
|
+
};
|
|
104
|
+
const connectAndDiscover = async (selection: Selection): Promise<{ activeConnection: StdioConnection; tools: DiscoveredTool[] }> => {
|
|
105
|
+
if (selection.composedOnly && !await (startupSupported ??= checkVersion(selection.project))) {
|
|
106
|
+
throw new Error('Screenplay optional startup requires Cratis CLI 3.46.1 or later.');
|
|
107
|
+
}
|
|
108
|
+
const activeConnection = connect(selection.project);
|
|
109
|
+
connection = activeConnection;
|
|
110
|
+
const tools = await discover(activeConnection);
|
|
111
|
+
if (connection !== activeConnection || activeConnection.stopped) throw new Error('Screenplay session ended during discovery.');
|
|
112
|
+
return { activeConnection, tools };
|
|
113
|
+
};
|
|
114
|
+
const reportUnavailable = (context: ExtensionContext): void => {
|
|
115
|
+
if (unavailableReported) return;
|
|
116
|
+
unavailableReported = true;
|
|
117
|
+
if (context.hasUI) context.ui.notify('Screenplay MCP is unavailable; install/update the Cratis CLI to 3.46.1 or later to enable it.', 'info');
|
|
118
|
+
};
|
|
119
|
+
const confirmationText = (parameters: Record<string, unknown>): string => {
|
|
120
|
+
const argumentsText = JSON.stringify(parameters);
|
|
121
|
+
if (argumentsText.length > 8192) throw new Error('Mutation confirmation arguments are too large; omit includeContent and use the proposal/operation identifiers.');
|
|
122
|
+
return argumentsText;
|
|
123
|
+
};
|
|
124
|
+
const confirmMutation = async (call: NativeCall, parameters: Record<string, unknown>, signal: AbortSignal | undefined, toolContext: ExtensionContext): Promise<void> => {
|
|
125
|
+
if (!toolContext.hasUI) throw new Error('Screenplay source mutation requires explicit user confirmation in Pi interactive/RPC mode.');
|
|
126
|
+
const argumentsText = confirmationText(parameters);
|
|
127
|
+
const approved = await toolContext.ui.confirm(`Screenplay ${call.tool.name}`, `Modify source under ${call.modelRoot}?\n${argumentsText}\nOnly approve the exact reviewed proposal or recovery operation.`, { timeout: 60_000, signal });
|
|
128
|
+
if (!approved || signal?.aborted) throw new Error('Screenplay source mutation was not approved.');
|
|
129
|
+
ensureCurrent(toolContext);
|
|
130
|
+
};
|
|
131
|
+
const isInvalidMutationResult = (call: NativeCall, response: unknown, toolCallId: string): boolean => call.tool.mutation && response !== undefined && !failures.has(toolCallId);
|
|
132
|
+
const recordFailure = (toolCallId: string, result: ReturnType<typeof mapResult>): never => {
|
|
133
|
+
if (failures.size >= 64) failures.delete(failures.keys().next().value!);
|
|
134
|
+
failures.set(toolCallId, failedResult(result));
|
|
135
|
+
throw new Error('Screenplay reported a failed tool call.');
|
|
136
|
+
};
|
|
137
|
+
const afterCallError = (call: NativeCall, response: unknown, toolCallId: string, error: unknown): never => {
|
|
138
|
+
if (isInvalidMutationResult(call, response, toolCallId)) {
|
|
139
|
+
uncertain = true;
|
|
140
|
+
dispose();
|
|
141
|
+
throw new ConnectionFailure('Screenplay mutation returned an invalid result.', true);
|
|
142
|
+
}
|
|
143
|
+
uncertain ||= call.activeConnection.outcomeUnknown;
|
|
144
|
+
if (call.activeConnection.stopped) deactivate();
|
|
145
|
+
throw error;
|
|
146
|
+
};
|
|
147
|
+
const forward = async (call: NativeCall, toolCallId: string, parameters: Record<string, unknown>, signal: AbortSignal | undefined) => {
|
|
148
|
+
let response: unknown;
|
|
72
149
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
activeConnection = connect(selection.project);
|
|
77
|
-
connection = activeConnection;
|
|
78
|
-
tools = await discover(activeConnection);
|
|
79
|
-
if (connection !== activeConnection || activeConnection.stopped) throw new Error('Screenplay session ended during discovery.');
|
|
150
|
+
response = await call.activeConnection.request('tools/call', { name: call.tool.name, arguments: parameters }, signal, call.tool.mutation);
|
|
151
|
+
const result = mapResult(response);
|
|
152
|
+
return result.details.isError ? recordFailure(toolCallId, result) : result;
|
|
80
153
|
} catch (error) {
|
|
154
|
+
return afterCallError(call, response, toolCallId, error);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
const assertCallable = (call: NativeCall, parameters: unknown, signal: AbortSignal | undefined, toolContext: ExtensionContext): Record<string, unknown> => {
|
|
158
|
+
ensureCurrent(toolContext);
|
|
159
|
+
if (connection !== call.activeConnection || !pi.getActiveTools().includes(call.tool.nativeName)) throw new Error('Screenplay tool is inactive in this session.');
|
|
160
|
+
if (!object(parameters)) throw new Error('Screenplay arguments must be an object.');
|
|
161
|
+
if (signal?.aborted) throw new Error('Screenplay call cancelled before sending.');
|
|
162
|
+
return parameters;
|
|
163
|
+
};
|
|
164
|
+
const registerNative = (call: NativeCall): void => {
|
|
165
|
+
const { tool } = call;
|
|
166
|
+
registered.add(tool.nativeName);
|
|
167
|
+
pi.registerTool({
|
|
168
|
+
name: tool.nativeName,
|
|
169
|
+
label: `Screenplay ${tool.name}`,
|
|
170
|
+
description: tool.description,
|
|
171
|
+
parameters: tool.parameters,
|
|
172
|
+
executionMode: 'sequential',
|
|
173
|
+
promptGuidelines: [
|
|
174
|
+
'Use the Screenplay model-authoring skill. Read/propose/review before applying; only a direct user request authorizes apply or recovery.',
|
|
175
|
+
'Use bounded pages. On an unknown mutation outcome, never retry or recover automatically; inspect workspace-state first.',
|
|
176
|
+
],
|
|
177
|
+
async execute(toolCallId, parameters, signal, _onUpdate, toolContext) {
|
|
178
|
+
const checked = assertCallable(call, parameters, signal, toolContext);
|
|
179
|
+
if (tool.mutation) await confirmMutation(call, checked, signal, toolContext);
|
|
180
|
+
return forward(call, toolCallId, checked, signal);
|
|
181
|
+
},
|
|
182
|
+
});
|
|
183
|
+
};
|
|
184
|
+
/** Never re-enable a user-disabled tool. SDK allow/exclude restrictions still filter registration. */
|
|
185
|
+
const restoreActive = (tools: DiscoveredTool[], oldNames: Set<string>, previouslyActive: Set<string>): void => {
|
|
186
|
+
const discovered = new Set(tools.map(tool => tool.nativeName));
|
|
187
|
+
const next = pi.getActiveTools().filter(name => !registered.has(name) || (discovered.has(name) && (!oldNames.has(name) || previouslyActive.has(name))));
|
|
188
|
+
for (const name of discovered) if (oldNames.has(name) && previouslyActive.has(name)) next.push(name);
|
|
189
|
+
pi.setActiveTools([...new Set(next)]);
|
|
190
|
+
paused.clear();
|
|
191
|
+
};
|
|
192
|
+
const registerAll = (tools: DiscoveredTool[], activeConnection: StdioConnection, selection: Selection, previouslyActive: Set<string>): void => {
|
|
193
|
+
const existing = new Set(pi.getAllTools().map(tool => tool.name));
|
|
194
|
+
if (tools.some(tool => existing.has(tool.nativeName) && !registered.has(tool.nativeName))) throw new Error('Screenplay native tool name conflicts with another extension.');
|
|
195
|
+
const oldNames = new Set(registered);
|
|
196
|
+
const modelRoot = selection.root ?? "the project's Screenplay model";
|
|
197
|
+
tools.forEach(tool => registerNative({ tool, activeConnection, modelRoot }));
|
|
198
|
+
restoreActive(tools, oldNames, previouslyActive);
|
|
199
|
+
};
|
|
200
|
+
const activate = async (context: ExtensionContext, selection: Selection, previouslyActive: Set<string>, explicit: boolean): Promise<void> => {
|
|
201
|
+
let found: Awaited<ReturnType<typeof connectAndDiscover>>;
|
|
202
|
+
try { found = await connectAndDiscover(selection); }
|
|
203
|
+
catch (error) {
|
|
81
204
|
dispose();
|
|
82
205
|
// Application-only composition makes MCP optional. Independent profile/root errors and uncertain mutations still surface.
|
|
83
|
-
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
if (context.hasUI) context.ui.notify('Screenplay MCP is unavailable; install/update the Cratis CLI to 3.46.1 or later to enable it.', 'info');
|
|
87
|
-
}
|
|
206
|
+
const surfaces = explicit || uncertain;
|
|
207
|
+
if (surfaces || !selection.composedOnly) throw error;
|
|
208
|
+
reportUnavailable(context);
|
|
88
209
|
return;
|
|
89
210
|
}
|
|
90
|
-
try {
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
|
|
94
|
-
for (const tool of tools) {
|
|
95
|
-
registered.add(tool.nativeName);
|
|
96
|
-
pi.registerTool({
|
|
97
|
-
name: tool.nativeName,
|
|
98
|
-
label: `Screenplay ${tool.name}`,
|
|
99
|
-
description: tool.description,
|
|
100
|
-
parameters: tool.parameters,
|
|
101
|
-
executionMode: 'sequential',
|
|
102
|
-
promptGuidelines: [
|
|
103
|
-
'Use the Screenplay model-authoring skill. Read/propose/review before applying; only a direct user request authorizes apply or recovery.',
|
|
104
|
-
'Use bounded pages. On an unknown mutation outcome, never retry or recover automatically; inspect workspace-state first.',
|
|
105
|
-
],
|
|
106
|
-
async execute(toolCallId, parameters, signal, _onUpdate, toolContext) {
|
|
107
|
-
ensureCurrent(toolContext);
|
|
108
|
-
if (connection !== activeConnection || !pi.getActiveTools().includes(tool.nativeName)) throw new Error('Screenplay tool is inactive in this session.');
|
|
109
|
-
if (!object(parameters)) throw new Error('Screenplay arguments must be an object.');
|
|
110
|
-
if (signal?.aborted) throw new Error('Screenplay call cancelled before sending.');
|
|
111
|
-
if (tool.mutation) {
|
|
112
|
-
if (!toolContext.hasUI) throw new Error('Screenplay source mutation requires explicit user confirmation in Pi interactive/RPC mode.');
|
|
113
|
-
const argumentsText = JSON.stringify(parameters);
|
|
114
|
-
if (argumentsText.length > 8192) throw new Error('Mutation confirmation arguments are too large; omit includeContent and use the proposal/operation identifiers.');
|
|
115
|
-
const approved = await toolContext.ui.confirm(`Screenplay ${tool.name}`, `Modify source under ${modelRoot}?\n${argumentsText}\nOnly approve the exact reviewed proposal or recovery operation.`, { timeout: 60_000, signal });
|
|
116
|
-
if (!approved || signal?.aborted) throw new Error('Screenplay source mutation was not approved.');
|
|
117
|
-
ensureCurrent(toolContext);
|
|
118
|
-
}
|
|
119
|
-
let response: unknown;
|
|
120
|
-
try {
|
|
121
|
-
response = await activeConnection.request('tools/call', { name: tool.name, arguments: parameters }, signal, tool.mutation);
|
|
122
|
-
const result = mapResult(response);
|
|
123
|
-
if (result.details.isError) {
|
|
124
|
-
if (failures.size >= 64) failures.delete(failures.keys().next().value!);
|
|
125
|
-
failures.set(toolCallId, failedResult(result));
|
|
126
|
-
throw new Error('Screenplay reported a failed tool call.');
|
|
127
|
-
}
|
|
128
|
-
return result;
|
|
129
|
-
} catch (error) {
|
|
130
|
-
if (tool.mutation && response !== undefined && !failures.has(toolCallId)) {
|
|
131
|
-
uncertain = true;
|
|
132
|
-
dispose();
|
|
133
|
-
throw new ConnectionFailure('Screenplay mutation returned an invalid result.', true);
|
|
134
|
-
}
|
|
135
|
-
uncertain ||= activeConnection.outcomeUnknown;
|
|
136
|
-
if (activeConnection.stopped) deactivate();
|
|
137
|
-
throw error;
|
|
138
|
-
}
|
|
139
|
-
},
|
|
140
|
-
});
|
|
141
|
-
}
|
|
142
|
-
// Never re-enable a user-disabled tool. SDK allow/exclude restrictions still filter registration.
|
|
143
|
-
const discovered = new Set(tools.map(tool => tool.nativeName));
|
|
144
|
-
const next = pi.getActiveTools().filter(name => !registered.has(name) || (discovered.has(name) && (!oldNames.has(name) || previouslyActive.has(name))));
|
|
145
|
-
for (const name of discovered) if (oldNames.has(name) && previouslyActive.has(name)) next.push(name);
|
|
146
|
-
pi.setActiveTools([...new Set(next)]);
|
|
147
|
-
paused.clear();
|
|
148
|
-
} catch (error) {
|
|
149
|
-
if (connection === activeConnection) dispose();
|
|
150
|
-
else activeConnection.dispose();
|
|
211
|
+
try { registerAll(found.tools, found.activeConnection, selection, previouslyActive); }
|
|
212
|
+
catch (error) {
|
|
213
|
+
if (connection === found.activeConnection) dispose();
|
|
214
|
+
else found.activeConnection.dispose();
|
|
151
215
|
throw error;
|
|
152
216
|
}
|
|
153
217
|
};
|
|
@@ -160,7 +224,7 @@ export function registerBridge(pi: ExtensionAPI, corpus: string, connect = start
|
|
|
160
224
|
};
|
|
161
225
|
pi.on('session_start', (_event, context) => refreshAll(context, true));
|
|
162
226
|
pi.on('before_agent_start', async (_event, context) => { await refreshAll(context, false); });
|
|
163
|
-
pi.on('session_shutdown', () => { dispose(); servers.dispose(); failures.clear(); });
|
|
227
|
+
pi.on('session_shutdown', () => { dispose(); servers.dispose(); failures.clear(); activation.publish(owner, new Map()); });
|
|
164
228
|
pi.on('tool_result', event => {
|
|
165
229
|
if (!registered.has(event.toolName)) return;
|
|
166
230
|
const failure = failures.get(event.toolCallId);
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { object, readJson, resolveProfiles, supportedSchema } from './configuration.ts';
|
|
6
|
-
import type {
|
|
6
|
+
import type { ServerSelection } from './CorpusServer.ts';
|
|
7
7
|
|
|
8
8
|
const validId = /^[A-Za-z0-9_-]+$/;
|
|
9
9
|
|
|
@@ -22,13 +22,20 @@ function problem(entry: Record<string, unknown>): string | undefined {
|
|
|
22
22
|
return undefined;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
if (override
|
|
31
|
-
|
|
25
|
+
type Override = { enabled: boolean; eager: boolean } | { error: string };
|
|
26
|
+
|
|
27
|
+
/** `mcpServers.<id>`: `enabled: false` opts out, `eager: true` registers at session start; a non-boolean is an error for that server only. */
|
|
28
|
+
function readOverride(overrides: unknown, id: string): Override {
|
|
29
|
+
const override = object(overrides) ? overrides[id] : undefined;
|
|
30
|
+
if (override === undefined) return { enabled: true, eager: false };
|
|
31
|
+
if (!object(override)) return { error: 'the mcpServers configuration must be an object' };
|
|
32
|
+
if (override.enabled === false) return { enabled: false, eager: false };
|
|
33
|
+
const error = invalidFlag(override.enabled, 'enabled') ?? invalidFlag(override.eager, 'eager');
|
|
34
|
+
return error ? { error } : { enabled: true, eager: override.eager === true };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function invalidFlag(value: unknown, name: string): string | undefined {
|
|
38
|
+
return value === undefined || typeof value === 'boolean' ? undefined : `mcpServers ${name} must be a boolean`;
|
|
32
39
|
}
|
|
33
40
|
|
|
34
41
|
/** Select every stdio server whose profiles intersect the explicitly listed profiles (never composed ones), except Screenplay which keeps its own path. */
|
|
@@ -67,10 +74,10 @@ export function selectedCorpusServers(project: string, corpus: string): ServerSe
|
|
|
67
74
|
const invalid = problem(entry);
|
|
68
75
|
if (invalid) { selection.messages.push(`${label} was skipped: ${invalid}.`); continue; }
|
|
69
76
|
const id = entry.id as string;
|
|
70
|
-
const
|
|
71
|
-
if (
|
|
72
|
-
if (
|
|
73
|
-
selection.servers.push({ id, command: entry.command as string, args: entry.args as string[], env: { ...(entry.env as Record<string, string> | undefined) } });
|
|
77
|
+
const override = readOverride(overrides, id);
|
|
78
|
+
if ('error' in override) { selection.messages.push(`${label} was skipped: ${override.error}.`); continue; }
|
|
79
|
+
if (!override.enabled) continue;
|
|
80
|
+
selection.servers.push({ id, command: entry.command as string, args: entry.args as string[], env: { ...(entry.env as Record<string, string> | undefined) }, eager: override.eager });
|
|
74
81
|
}
|
|
75
82
|
return selection;
|
|
76
83
|
}
|
|
@@ -45,8 +45,10 @@ servers. Deselecting/uninstalling removes only unchanged owned entries. Foreign
|
|
|
45
45
|
or modified entries remain conflicts, even with force. Resolve a conflict by
|
|
46
46
|
intentionally renaming/removing your entry or disabling that server with
|
|
47
47
|
`mcpServers.<id>.enabled = false` in the project configuration; do not overwrite
|
|
48
|
-
it speculatively. Pi
|
|
49
|
-
|
|
48
|
+
it speculatively. In Pi, the native extension registers a selected server's tools on
|
|
49
|
+
demand: the model calls `cratis_enable_mcp` with the server id and the tools appear from
|
|
50
|
+
the next step. `mcpServers.<id>.eager = true` (Pi only, boolean) registers them at
|
|
51
|
+
session start instead. An invalid selected descriptor is reported
|
|
50
52
|
and skipped; successful guidance installation does not prove MCP availability.
|
|
51
53
|
Installing a server does not authorize its tools or commands.
|
|
52
54
|
|
|
@@ -11,6 +11,12 @@ Read [preferred syntax](../cratis-screenplay-toolchain/references/preferred-synt
|
|
|
11
11
|
Prefer the Screenplay MCP tools to text/regex edits: the compiler owns declaration,
|
|
12
12
|
reference, hierarchy and source evidence for the declarative document set.
|
|
13
13
|
|
|
14
|
+
In Pi the Screenplay tools are not registered at session start: call
|
|
15
|
+
`cratis_enable_mcp` with `{"server": "screenplay"}` first. The `screenplay_*` tools are
|
|
16
|
+
available from the next step, not in the same parallel tool batch, so enable alone, then
|
|
17
|
+
use them. Other harnesses expose the tools natively; skip this there. A project
|
|
18
|
+
that sets `mcpServers.screenplay.eager` to `true` already has them.
|
|
19
|
+
|
|
14
20
|
**Valid source is not necessarily executable.** Stage owns rendering/runtime
|
|
15
21
|
admission. Read the [language reference](references/language-reference.md) for
|
|
16
22
|
construct syntax, source-versus-execution states and a complete compiled model.
|