-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathindex.ts
More file actions
472 lines (426 loc) · 18.1 KB
/
Copy pathindex.ts
File metadata and controls
472 lines (426 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { loadConfig, isMissingCredentialsError } from "./config.js";
import { ContextStreamClient } from "./client.js";
import { registerTools, setupClientDetection, registerLimitedTools } from "./tools.js";
import { registerResources } from "./resources.js";
import { registerPrompts } from "./prompts.js";
import { SessionManager } from "./session-manager.js";
import { runHttpGateway } from "./http-gateway.js";
import { existsSync, mkdirSync, writeFileSync } from "fs";
import { homedir } from "os";
import { join } from "path";
import { VERSION, checkForUpdates } from "./version.js";
import { runSetupWizard } from "./setup.js";
import { readSavedCredentials } from "./credentials.js";
const ENABLE_PROMPTS =
(process.env.CONTEXTSTREAM_ENABLE_PROMPTS || "true").toLowerCase() !== "false";
/**
* Check if this is the first run and show star message if so.
* Only shows once per install to avoid being annoying.
*/
function showFirstRunMessage(): void {
const configDir = join(homedir(), ".contextstream");
const starShownFile = join(configDir, ".star-shown");
// Check if we've already shown the message
if (existsSync(starShownFile)) {
return;
}
// Create config directory if it doesn't exist
if (!existsSync(configDir)) {
try {
mkdirSync(configDir, { recursive: true });
} catch {
// If we can't create the directory, skip the message
return;
}
}
// Show the star message
console.error("");
console.error("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.error("⭐ If ContextStream saves you time, please star the MCP server repo:");
console.error(" https://github.com/contextstream/mcp-server");
console.error(" It helps others discover it!");
console.error("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.error("");
// Mark as shown
try {
writeFileSync(starShownFile, new Date().toISOString());
} catch {
// Ignore write errors
}
}
function printHelp() {
// Keep help output on stdout so it is visible when run via npx
console.log(`ContextStream MCP Server (contextstream-mcp) v${VERSION}
Usage:
npx --prefer-online -y @contextstream/mcp-server@latest
contextstream-mcp
contextstream-mcp setup [--yes] [--dry-run] [--editors=claude,cursor] [--no-doctor]
contextstream-mcp doctor
contextstream-mcp index [path]
contextstream-mcp http
contextstream-mcp hook <hook-name>
Commands:
setup Onboarding wizard (rules + workspace mapping). --yes runs zero-prompt
with defaults; --editors=<csv> pre-selects editors; --no-doctor skips
the final verification step
doctor Read-only diagnostics: auth, API, folder scope, index health, rules, hooks
index [path] Index a project folder now (the wizard runs this in the background)
verify-key [--json] Verify API key and show account info
update-hooks [flags] Update hooks for all editors (Claude, Cursor, Cline, Roo, Kilo)
--scope=global Install hooks globally (default)
--scope=project, -p Install hooks for current project only
--path=/path Specify project path (implies --scope=project)
http Run HTTP MCP gateway (streamable HTTP transport)
hook pre-tool-use PreToolUse hook - blocks discovery tools, redirects to ContextStream
hook user-prompt-submit UserPromptSubmit hook - injects ContextStream rules reminder
hook media-aware Media-aware hook - detects media prompts, injects media tool guidance
hook pre-compact PreCompact hook - saves conversation state before compaction
hook post-compact PostCompact hook - restores context after compaction
hook session-start SessionStart hook alias for session-init
hook stop Stop hook alias for session-end
hook post-write PostToolUse hook - real-time file indexing after Edit/Write
hook post-tool-use PostToolUse hook alias for post-write
hook post-tool-use-failure PostToolUseFailure hook - captures repeated tool failures
hook notification Notification hook - captures runtime notifications
hook permission-request PermissionRequest hook - captures escalation requests
hook subagent-start SubagentStart hook - injects context for spawned agents
hook subagent-stop SubagentStop hook - captures subagent outcomes
hook task-completed TaskCompleted hook - updates tasks and captures completion
hook teammate-idle TeammateIdle hook - redirects idle teammates to pending tasks
hook auto-rules Legacy no-op hook
hook on-bash Legacy no-op hook
hook on-task Legacy no-op hook
hook on-read Legacy no-op hook
hook on-web Legacy no-op hook
hook session-init SessionStart hook - full context injection on session start
hook session-end Stop hook - finalizes session, saves state
hook on-save-intent UserPromptSubmit hook - redirects doc saves to ContextStream
Environment variables:
CONTEXTSTREAM_API_URL Base API URL (e.g. https://api.contextstream.io)
CONTEXTSTREAM_API_KEY API key for authentication (or use CONTEXTSTREAM_JWT)
CONTEXTSTREAM_JWT JWT for authentication (alternative to API key)
CONTEXTSTREAM_ALLOW_HEADER_AUTH Allow header-based auth when no API key/JWT is set
CONTEXTSTREAM_WORKSPACE_ID Optional default workspace ID
CONTEXTSTREAM_PROJECT_ID Optional default project ID
CONTEXTSTREAM_TOOLSET Tool mode: light|standard|complete (default: standard)
CONTEXTSTREAM_TOOL_SURFACE_PROFILE Tool surface: default|openai_agentic (default: default)
CONTEXTSTREAM_TOOL_ALLOWLIST Optional comma-separated tool names to expose (overrides toolset)
CONTEXTSTREAM_AUTO_TOOLSET Auto-detect client and adjust toolset (default: false)
CONTEXTSTREAM_AUTO_HIDE_INTEGRATIONS Auto-hide Slack/GitHub tools when not connected (default: true)
CONTEXTSTREAM_SCHEMA_MODE Schema verbosity: compact|full (default: full, compact reduces tokens)
CONTEXTSTREAM_PROGRESSIVE_MODE Progressive disclosure: true|false (default: false, starts with ~13 core tools)
CONTEXTSTREAM_ROUTER_MODE Router pattern: true|false (default: false, exposes only 2 meta-tools)
CONTEXTSTREAM_OUTPUT_FORMAT Output verbosity: compact|pretty (default: compact, ~30% fewer tokens)
CONTEXTSTREAM_INCLUDE_STRUCTURED_CONTENT Include structured JSON payloads in tool results: true|false (default: true)
CONTEXTSTREAM_SEARCH_LIMIT Default MCP search limit (default: 3)
CONTEXTSTREAM_SEARCH_MAX_CHARS Max chars per search result content (default: 400)
CONTEXTSTREAM_CONSOLIDATED Consolidated domain tools: true|false (default: true in v0.4.x, ~75% token reduction)
CONTEXTSTREAM_CONTEXT_PACK Enable Context Pack in context_smart: true|false (default: true)
CONTEXTSTREAM_PRO_TOOLS Optional comma-separated PRO tool names (default: AI tools)
CONTEXTSTREAM_UPGRADE_URL Optional upgrade URL shown for PRO tools on Free plan
CONTEXTSTREAM_ENABLE_PROMPTS Enable MCP prompts list (default: true)
MCP_HTTP_HOST HTTP gateway host (default: 0.0.0.0)
MCP_HTTP_PORT HTTP gateway port (default: 8787)
MCP_HTTP_PATH HTTP gateway path (default: /mcp)
MCP_HTTP_REQUIRE_AUTH Require auth headers for HTTP gateway (default: true)
MCP_HTTP_JSON_RESPONSE Enable JSON responses (default: false)
Examples:
CONTEXTSTREAM_API_URL="https://api.contextstream.io" \\
CONTEXTSTREAM_API_KEY="your_api_key" \\
npx --prefer-online -y @contextstream/mcp-server@latest
Setup wizard:
npx --prefer-online -y @contextstream/mcp-server@latest setup
Notes:
- When used from an MCP client (e.g. Codex, Cursor, VS Code),
set these env vars in the client's MCP server configuration.
- The server communicates over stdio; logs are written to stderr.`);
}
/**
* Run the MCP server in limited mode (no credentials).
* Only exposes a setup helper tool so users know how to configure.
*/
async function runLimitedModeServer(): Promise<void> {
const server = new McpServer({
name: "contextstream-mcp",
version: VERSION,
});
registerLimitedTools(server);
console.error(`ContextStream MCP server v${VERSION} (limited mode)`);
console.error('Run "npx --prefer-online -y @contextstream/mcp-server@latest setup" to enable all tools.');
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("ContextStream MCP server connected (limited mode - setup required)");
}
async function main() {
const args = process.argv.slice(2);
if (args.includes("--help") || args.includes("-h")) {
printHelp();
return;
}
if (args.includes("--version") || args.includes("-v")) {
console.log(`contextstream-mcp v${VERSION}`);
return;
}
if (args[0] === "setup") {
await runSetupWizard(args.slice(1));
return;
}
if (args[0] === "doctor") {
const { runDoctor } = await import("./doctor.js");
await runDoctor();
return;
}
if (args[0] === "index") {
const { runIndexCommand } = await import("./setup.js");
await runIndexCommand(args[1] || process.cwd());
return;
}
if (args[0] === "http") {
if (
!process.env.CONTEXTSTREAM_API_KEY &&
!process.env.CONTEXTSTREAM_JWT &&
!process.env.CONTEXTSTREAM_ALLOW_HEADER_AUTH
) {
process.env.CONTEXTSTREAM_ALLOW_HEADER_AUTH = "true";
}
await runHttpGateway();
return;
}
// Hook command: runs editor hooks (Node.js-based, no Python dependency)
if (args[0] === "hook") {
const hookName = args[1];
switch (hookName) {
case "post-tool-use": {
const { runPostWriteHook } = await import("./hooks/post-write.js");
await runPostWriteHook();
return;
}
case "post-write": {
const { runPostWriteHook } = await import("./hooks/post-write.js");
await runPostWriteHook();
return;
}
case "post-tool-use-failure": {
const { runPostToolUseFailureHook } = await import("./hooks/post-tool-use-failure.js");
await runPostToolUseFailureHook();
return;
}
case "notification": {
const { runNotificationHook } = await import("./hooks/notification.js");
await runNotificationHook();
return;
}
case "permission-request": {
const { runPermissionRequestHook } = await import("./hooks/permission-request.js");
await runPermissionRequestHook();
return;
}
case "subagent-start": {
const { runSubagentStartHook } = await import("./hooks/subagent-start.js");
await runSubagentStartHook();
return;
}
case "subagent-stop": {
const { runSubagentStopHook } = await import("./hooks/subagent-stop.js");
await runSubagentStopHook();
return;
}
case "task-completed": {
const { runTaskCompletedHook } = await import("./hooks/task-completed.js");
await runTaskCompletedHook();
return;
}
case "teammate-idle": {
const { runTeammateIdleHook } = await import("./hooks/teammate-idle.js");
await runTeammateIdleHook();
return;
}
case "pre-tool-use": {
const { runPreToolUseHook } = await import("./hooks/pre-tool-use.js");
await runPreToolUseHook();
return;
}
case "user-prompt-submit": {
const { runUserPromptSubmitHook } = await import("./hooks/user-prompt-submit.js");
await runUserPromptSubmitHook();
return;
}
case "media-aware": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "pre-compact": {
const { runPreCompactHook } = await import("./hooks/pre-compact.js");
await runPreCompactHook();
return;
}
case "auto-rules": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "post-compact": {
const { runPostCompactHook } = await import("./hooks/post-compact.js");
await runPostCompactHook();
return;
}
case "on-bash": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "on-task": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "on-read": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "on-web": {
const { runNoopHook } = await import("./hooks/noop.js");
await runNoopHook();
return;
}
case "session-start":
case "session-init": {
const { runSessionInitHook } = await import("./hooks/session-init.js");
await runSessionInitHook();
return;
}
case "stop": {
const { runStopHook } = await import("./hooks/stop.js");
await runStopHook();
return;
}
case "session-end": {
const { runSessionEndHook } = await import("./hooks/session-end.js");
await runSessionEndHook();
return;
}
case "on-save-intent": {
const { runOnSaveIntentHook } = await import("./hooks/on-save-intent.js");
await runOnSaveIntentHook();
return;
}
default:
// Unknown hook - exit 0 to avoid "hook error" in editors.
// This happens when users have hooks from a newer version but run an older cached binary.
process.exit(0);
}
}
// Verify API key command: validate key and show account info
// Usage: contextstream-mcp verify-key [--json]
if (args[0] === "verify-key") {
const { runVerifyKey } = await import("./verify-key.js");
const outputJson = args.includes("--json");
const result = await runVerifyKey(outputJson);
process.exit(result.valid ? 0 : 1);
}
// Update hooks command: non-interactive hook installation for all editors
// Usage: contextstream-mcp update-hooks [--scope=global|project] [--path=/project/path]
if (args[0] === "update-hooks") {
const { installAllEditorHooks } = await import("./hooks-config.js");
// Parse flags
let scope: "global" | "project" = "global";
let projectPath: string | undefined;
for (const arg of args.slice(1)) {
if (arg === "--scope=project" || arg === "-p") {
scope = "project";
projectPath = projectPath || process.cwd();
} else if (arg === "--scope=global" || arg === "-g") {
scope = "global";
} else if (arg.startsWith("--path=")) {
projectPath = arg.replace("--path=", "");
scope = "project";
}
}
const scopeLabel = scope === "project" ? `project (${projectPath || process.cwd()})` : "global";
console.error(`Updating hooks for all editors (${scopeLabel})...`);
try {
const results = await installAllEditorHooks({
scope,
projectPath: scope === "project" ? (projectPath || process.cwd()) : undefined
});
for (const result of results) {
console.error(`✓ ${result.editor}: ${result.installed.length} hooks installed`);
}
console.error("✓ Hooks updated successfully");
} catch (error) {
console.error("Failed to update hooks:", error);
process.exit(1);
}
return;
}
// Try to load saved credentials if env vars not set
if (!process.env.CONTEXTSTREAM_API_KEY && !process.env.CONTEXTSTREAM_JWT) {
const saved = await readSavedCredentials();
if (saved) {
process.env.CONTEXTSTREAM_API_URL = saved.api_url;
process.env.CONTEXTSTREAM_API_KEY = saved.api_key;
}
}
// Try to load config - may fail if still no credentials
let config;
try {
config = loadConfig();
} catch (err) {
if (isMissingCredentialsError(err)) {
// Run limited mode server instead of exiting with error
await runLimitedModeServer();
return;
}
throw err;
}
const client = new ContextStreamClient(config);
const server = new McpServer({
name: "contextstream-mcp",
version: VERSION,
});
// Set up client detection callback (Strategy 3 - Option B Primary)
// This will detect token-sensitive clients (Claude Code, Claude Desktop) on MCP initialize
setupClientDetection(server);
// Create session manager for auto-context feature
// This enables automatic context loading on the FIRST tool call of any session
const sessionManager = new SessionManager(server, client);
// Register all MCP components with auto-context enabled
registerTools(server, client, sessionManager, {
toolSurfaceProfile: config.toolSurfaceProfile,
});
registerResources(server, client, config.apiUrl);
if (ENABLE_PROMPTS) {
registerPrompts(server);
}
// Log startup info (respects CONTEXTSTREAM_LOG_LEVEL)
const logLevel = (process.env.CONTEXTSTREAM_LOG_LEVEL || "normal").toLowerCase();
const logQuiet = logLevel === "quiet";
const logVerbose = logLevel === "verbose";
if (!logQuiet) {
console.error(`━━━ ContextStream v${VERSION} ━━━`);
}
if (logVerbose) {
console.error(` API: ${config.apiUrl}`);
console.error(` Auth: ${config.apiKey ? "API Key" : config.jwt ? "JWT" : "None"}`);
}
// Start stdio transport (works with Claude Code, Cursor, VS Code MCP config, Inspector)
const transport = new StdioServerTransport();
await server.connect(transport);
if (!logQuiet) {
console.error("✓ ready");
}
// Show first-run star message (only once per install)
showFirstRunMessage();
// Check for updates in the background (non-blocking)
checkForUpdates().catch(() => {
// Silently ignore update check errors
});
}
main().catch((err) => {
console.error("ContextStream MCP server failed to start:", err?.message || err);
process.exit(1);
});