@thinkrun/mcp 0.3.14 → 0.3.16

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 (64) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +34 -2
  3. package/dist/bin/thinkrun-mcp.js +51 -11
  4. package/dist/bin/thinkrun-mcp.js.map +1 -1
  5. package/dist/shared/analysis-plans.d.ts +10 -0
  6. package/dist/shared/analysis-plans.js +12 -0
  7. package/dist/shared/batch-steps.d.ts +49 -0
  8. package/dist/shared/batch-steps.js +171 -0
  9. package/dist/shared/batch-steps.test.js +127 -0
  10. package/dist/shared/group-binding-key.d.ts +5 -0
  11. package/dist/shared/group-binding-key.js +15 -0
  12. package/dist/shared/group-binding-key.test.js +50 -0
  13. package/dist/shared/issue-report.d.ts +10 -0
  14. package/dist/shared/issue-report.js +126 -0
  15. package/dist/shared/issue-report.test.ts +110 -0
  16. package/dist/shared/native-type-budget.d.ts +16 -0
  17. package/dist/shared/native-type-budget.js +28 -0
  18. package/dist/shared/navigation-retry.d.ts +2 -0
  19. package/dist/shared/navigation-retry.js +26 -0
  20. package/dist/shared/navigation-retry.test.js +25 -0
  21. package/dist/shared/onboarding-drips.d.ts +13 -0
  22. package/dist/shared/onboarding-drips.js +100 -0
  23. package/dist/shared/onboarding-metrics.d.ts +4 -0
  24. package/dist/shared/onboarding-metrics.js +53 -0
  25. package/dist/shared/onboarding-public-consent.cjs +3 -0
  26. package/dist/shared/onboarding-public-consent.d.ts +1 -0
  27. package/dist/shared/onboarding-public-consent.js +3 -0
  28. package/dist/shared/onboarding-public-consent.json +3 -0
  29. package/dist/shared/recording-upload.js +11 -4
  30. package/dist/shared/recording-upload.test.js +16 -0
  31. package/dist/shared/selector-hints.d.ts +1 -0
  32. package/dist/shared/selector-hints.js +43 -0
  33. package/dist/shared/selector-hints.test.js +31 -0
  34. package/dist/shared/slack-report.d.ts +21 -0
  35. package/dist/shared/slack-report.js +381 -0
  36. package/dist/src/account-connection.d.ts +7 -0
  37. package/dist/src/account-connection.d.ts.map +1 -0
  38. package/dist/src/account-connection.js +37 -0
  39. package/dist/src/account-connection.js.map +1 -0
  40. package/dist/src/client.d.ts +14 -0
  41. package/dist/src/client.d.ts.map +1 -1
  42. package/dist/src/cloud-client.d.ts +2 -0
  43. package/dist/src/cloud-client.d.ts.map +1 -1
  44. package/dist/src/cloud-client.js +8 -0
  45. package/dist/src/cloud-client.js.map +1 -1
  46. package/dist/src/local-client.d.ts +23 -4
  47. package/dist/src/local-client.d.ts.map +1 -1
  48. package/dist/src/local-client.js +148 -49
  49. package/dist/src/local-client.js.map +1 -1
  50. package/dist/src/local-saving.d.ts +51 -0
  51. package/dist/src/local-saving.d.ts.map +1 -0
  52. package/dist/src/local-saving.js +150 -0
  53. package/dist/src/local-saving.js.map +1 -0
  54. package/dist/src/onboarding.d.ts +1 -1
  55. package/dist/src/onboarding.js +1 -1
  56. package/dist/src/recordings.d.ts +29 -0
  57. package/dist/src/recordings.d.ts.map +1 -0
  58. package/dist/src/recordings.js +68 -0
  59. package/dist/src/recordings.js.map +1 -0
  60. package/dist/src/server.d.ts +25 -1
  61. package/dist/src/server.d.ts.map +1 -1
  62. package/dist/src/server.js +182 -43
  63. package/dist/src/server.js.map +1 -1
  64. package/package.json +6 -5
@@ -5,6 +5,7 @@
5
5
  * script injection attempts. The server-side also applies JSON.stringify()
6
6
  * escaping when embedding selectors in error messages (defense-in-depth).
7
7
  */
8
+ import { BATCH_ACTIONS, MAX_BATCH_STEPS, runBatchSteps, validateBatchSteps } from '../shared/batch-steps.js';
8
9
  import { existsSync, readFileSync } from 'node:fs';
9
10
  import { homedir } from 'node:os';
10
11
  import { join } from 'node:path';
@@ -13,6 +14,7 @@ import { readTabAuditState, resolveTabAuditState, writeTabAuditState, } from '..
13
14
  import { patchLocalAuditState } from '../shared/local-audit-sync.js';
14
15
  import { uploadRecordingFile, RecordingUploadError } from '../shared/recording-upload.js';
15
16
  import { z } from 'zod';
17
+ import { recordingsListSchema } from './recordings.js';
16
18
  import { readNearestPackageVersion } from './package-version.js';
17
19
  const MCP_PACKAGE_VERSION = readNearestPackageVersion(import.meta.url);
18
20
  /** Zod schema for CSS selectors — rejects obvious script injection patterns. */
@@ -63,6 +65,59 @@ const pageCacheToolOptionsSchema = z
63
65
  textFormat: z.literal('plain').optional(),
64
66
  })
65
67
  .optional();
68
+ /** Tools the local client can only answer with "only available in cloud mode". */
69
+ export const CLOUD_ONLY_TOOLS = [
70
+ 'session_artifacts',
71
+ 'task_create',
72
+ 'task_execute',
73
+ 'task_status',
74
+ 'agent_identity',
75
+ 'browser_request_control',
76
+ 'browser_grant_status',
77
+ 'browser_release_control',
78
+ ];
79
+ /** Core tools for driving a browser, exposed by `--toolset browser`. */
80
+ export const BROWSER_TOOLSET = [
81
+ 'navigate', 'go_back', 'go_forward',
82
+ 'snapshot', 'screenshot', 'extract', 'evaluate', 'get_url',
83
+ 'batch_actions', 'click', 'fill', 'type_text', 'press_key', 'hover', 'scroll', 'select_option',
84
+ 'wait_for_element', 'wait_for_text', 'handle_dialog', 'console_messages', 'network_requests',
85
+ 'tab_list', 'tab_new', 'tab_close', 'tab_attach', 'tab_switch',
86
+ ];
87
+ /** Added to BROWSER_TOOLSET in cloud mode, where no session exists until one is created. */
88
+ export const BROWSER_TOOLSET_CLOUD_SESSION_TOOLS = ['session_create', 'session_wait_ready', 'session_delete'];
89
+ /** Run one validated batch step through the MCP client. */
90
+ function executeBatchStep(client, sessionId, step) {
91
+ switch (step.action) {
92
+ case 'navigate': return client.navigate(sessionId, { url: step.url });
93
+ case 'click': return client.click(sessionId, { selector: step.selector });
94
+ case 'fill': return client.fill(sessionId, { selector: step.selector, value: step.value });
95
+ case 'type': return client.type(sessionId, { selector: step.selector, text: step.text });
96
+ case 'press': return client.press(sessionId, { key: step.key });
97
+ case 'select': return client.select(sessionId, { selector: step.selector, value: step.value });
98
+ case 'hover': return client.hover(sessionId, { selector: step.selector });
99
+ case 'wait':
100
+ return step.selector !== undefined
101
+ ? client.wait(sessionId, { selector: step.selector })
102
+ : new Promise((resolve) => setTimeout(() => resolve({ success: true }), step.ms));
103
+ case 'wait_for_text': return client.waitForText(sessionId, { text: step.text });
104
+ case 'evaluate': return client.evaluate(sessionId, { script: step.script, timeout: 30_000 });
105
+ default: {
106
+ const unhandled = step;
107
+ throw new Error(`Unhandled batch action: ${JSON.stringify(unhandled)}`);
108
+ }
109
+ }
110
+ }
111
+ /** Validate every step, then run them in order, stopping at the first failure. */
112
+ export async function handleBatchActions(client, args, resolveSessionId) {
113
+ const validation = validateBatchSteps(args.steps);
114
+ if (!validation.ok) {
115
+ return { content: [{ type: 'text', text: JSON.stringify({ success: false, error: validation.error }) }], isError: true };
116
+ }
117
+ const sessionId = resolveSessionId();
118
+ const result = await runBatchSteps(validation.steps, (step) => executeBatchStep(client, sessionId, step));
119
+ return { content: [{ type: 'text', text: JSON.stringify(result) }], isError: !result.success };
120
+ }
66
121
  export const MAX_GET_HTML_CHARS = 200_000;
67
122
  export const MAX_SLEEP_MS = 30_000;
68
123
  const LOCAL_TOOL_ENRICH_TIMEOUT_MS = 300;
@@ -236,6 +291,9 @@ export function applyLifecycleDefaultSession(args) {
236
291
  case 'tab_attach':
237
292
  case 'window_new':
238
293
  return args.resultSessionId ?? args.currentDefaultSessionId;
294
+ case 'tab_new':
295
+ // A new tab becomes the default only when nothing is bound, so it never moves an agent off its attached tab.
296
+ return args.currentDefaultSessionId ?? args.resultSessionId;
239
297
  case 'tab_switch':
240
298
  case 'tab_focus':
241
299
  return args.currentDefaultSessionId;
@@ -291,6 +349,38 @@ export async function handleTabAttach(client, args, defaultSessionRef) {
291
349
  return buildLocalToolErrorResult(client, err);
292
350
  }
293
351
  }
352
+ export async function handleTabNew(client, args, defaultSessionRef) {
353
+ try {
354
+ const result = await client.newTab(args.sessionId ?? defaultSessionRef.current ?? '', args.url);
355
+ defaultSessionRef.current = applyLifecycleDefaultSession({
356
+ currentDefaultSessionId: defaultSessionRef.current,
357
+ operation: 'tab_new',
358
+ resultSessionId: result.tabId === undefined ? undefined : String(result.tabId),
359
+ });
360
+ return {
361
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
362
+ isError: false,
363
+ };
364
+ }
365
+ catch (err) {
366
+ return buildLocalToolErrorResult(client, err);
367
+ }
368
+ }
369
+ /** Close a tab and clear the default session if it pointed at that tab. */
370
+ export async function handleTabClose(client, args, sessionId, defaultSessionRef) {
371
+ const result = await client.closeTab(sessionId, args.tabId);
372
+ if (result.success) {
373
+ const tabIdOf = (id) => id.replace(/^local-/, '');
374
+ const closedTabId = args.tabId === undefined ? tabIdOf(sessionId) : String(args.tabId);
375
+ if (defaultSessionRef.current && tabIdOf(defaultSessionRef.current) === closedTabId) {
376
+ defaultSessionRef.current = undefined;
377
+ }
378
+ }
379
+ return {
380
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
381
+ isError: !result.success,
382
+ };
383
+ }
294
384
  export async function handleTabSwitch(client, args, defaultSessionRef) {
295
385
  try {
296
386
  const result = await client.switchToTab(args.tabId);
@@ -731,12 +821,12 @@ export function createServer(client, options) {
731
821
  // so concurrent calls are not expected, but future transports may allow pipelining.
732
822
  const c = clientRef ? () => clientRef.current : () => client;
733
823
  const requiredSessionIdSchema = z.string().describe('The session ID');
734
- const defaultableSessionIdSchema = z.string().optional().describe('The session ID (auto-injected if omitted when a default session exists)');
824
+ const defaultableSessionIdSchema = z.string().optional().describe('Session ID. Defaults to the current session.');
735
825
  /** Resolve session ID: use provided value, then ref, then initial default. */
736
826
  function sid(args) {
737
827
  const id = args.sessionId ?? sessionStateRef.current;
738
828
  if (!id)
739
- throw new Error('sessionId is required (no default session configured)');
829
+ throw new Error('sessionId is required (no default session configured). Open a tab with tab_new or tab_attach, or pass sessionId.');
740
830
  return id;
741
831
  }
742
832
  const remoteScopeEnum = z.enum([
@@ -750,15 +840,46 @@ export function createServer(client, options) {
750
840
  const effectiveDefault = sessionStateRef.current;
751
841
  const server = new McpServer({ name: 'thinkrun', version: MCP_PACKAGE_VERSION }, {
752
842
  capabilities: { tools: {} },
753
- instructions: effectiveDefault
754
- ? 'ThinkRun MCP server provides browser automation tools. ' +
755
- `A browser session is already active (ID: ${effectiveDefault}). ` +
756
- 'Use navigation and interaction tools directly — no need to create a session. ' +
757
- 'Always include a "thought" parameter to document your reasoning.'
758
- : 'ThinkRun MCP server provides browser automation tools. ' +
759
- 'Create a session first, then use navigation and interaction tools. ' +
760
- 'Always include a "thought" parameter to document your reasoning.',
843
+ instructions: options?.resolvedMode === 'local' && !effectiveDefault
844
+ ? 'ThinkRun MCP server controls the local browser. Open a tab with tab_new or attach to one with tab_attach, ' +
845
+ 'then use navigation and interaction tools. Relay the returned accountHint if present. When the user wants a saved audit, use save_local_session.'
846
+ : effectiveDefault
847
+ ? 'ThinkRun MCP server provides browser automation tools. ' +
848
+ `A browser session is already active (ID: ${effectiveDefault}). ` +
849
+ 'Use navigation and interaction tools directly — no need to create a session. ' +
850
+ 'Always include a "thought" parameter to document your reasoning.'
851
+ : 'ThinkRun MCP server provides browser automation tools. ' +
852
+ 'Create a session first, then use navigation and interaction tools. ' +
853
+ 'Always include a "thought" parameter to document your reasoning.',
761
854
  });
855
+ // Keep a handle on each tool so the list can follow the mode without re-registering anything.
856
+ const registeredTools = new Map();
857
+ const registerTool = server.registerTool.bind(server);
858
+ server.registerTool = (name, ...rest) => {
859
+ const tool = registerTool(name, ...rest);
860
+ registeredTools.set(name, tool);
861
+ return tool;
862
+ };
863
+ const applyToolVisibility = (mode) => {
864
+ const hideCloudOnly = mode === 'local';
865
+ const toolsetNames = new Set([
866
+ ...BROWSER_TOOLSET,
867
+ 'set_mode',
868
+ ...(mode === 'local' ? ['save_local_session', 'set_auditing', 'session_status', 'session_release'] : []),
869
+ ...(mode === 'cloud' ? BROWSER_TOOLSET_CLOUD_SESSION_TOOLS : []),
870
+ ]);
871
+ for (const [name, tool] of registeredTools) {
872
+ const visible = options?.toolset === 'browser'
873
+ ? toolsetNames.has(name)
874
+ : (name !== 'save_local_session' || mode === 'local') && !(hideCloudOnly && CLOUD_ONLY_TOOLS.includes(name));
875
+ if (visible !== tool.enabled) {
876
+ if (visible)
877
+ tool.enable();
878
+ else
879
+ tool.disable();
880
+ }
881
+ }
882
+ };
762
883
  // This intentionally bypasses the browser extension/native bridge. MCP receives only an
763
884
  // explicit local path; the shared client streams that file directly to the authenticated API.
764
885
  server.registerTool('recording_upload', {
@@ -820,6 +941,17 @@ export function createServer(client, options) {
820
941
  }],
821
942
  };
822
943
  });
944
+ server.registerTool('save_local_session', {
945
+ title: 'Save local browser work to ThinkRun',
946
+ description: 'When the user wants a saved audit, start saving subsequent action names and requested screenshots for the selected local tab to their ThinkRun account. Returns a receipt and dashboard link on success.',
947
+ inputSchema: { sessionId: defaultableSessionIdSchema },
948
+ }, async (args) => {
949
+ const client = c();
950
+ if (!client.saveLocalSession)
951
+ throw new Error('Saving a local audit requires local mode.');
952
+ const result = await client.saveLocalSession(sid(args));
953
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
954
+ });
823
955
  server.registerTool('session_status', {
824
956
  title: 'Get Session Status',
825
957
  description: 'Get the current status of a browser session including URL, title, and action count. '
@@ -981,10 +1113,19 @@ export function createServer(client, options) {
981
1113
  try {
982
1114
  const result = await onSetMode(args.mode);
983
1115
  clientRef.current = result.client;
1116
+ applyToolVisibility(result.resolvedMode);
984
1117
  return {
985
1118
  content: [{
986
1119
  type: 'text',
987
- text: JSON.stringify({ success: true, mode: args.mode, resolvedMode: result.resolvedMode }, null, 2),
1120
+ text: JSON.stringify({
1121
+ success: true,
1122
+ mode: args.mode,
1123
+ resolvedMode: result.resolvedMode,
1124
+ // MCP instructions are fixed at startup, so say here what changed.
1125
+ nextStep: result.resolvedMode === 'cloud'
1126
+ ? 'Create a browser session with session_create.'
1127
+ : 'Open a tab with tab_new or attach to one with tab_attach.',
1128
+ }, null, 2),
988
1129
  }],
989
1130
  };
990
1131
  }
@@ -1052,6 +1193,21 @@ export function createServer(client, options) {
1052
1193
  };
1053
1194
  }
1054
1195
  }
1196
+ server.registerTool('recordings_list', {
1197
+ title: 'List recording sessions',
1198
+ description: 'List account human feedback recordings from GET /api/feedback/recordings (no browser session). ' +
1199
+ 'Requires THINKRUN_API_KEY; local mode uses the configured cloud API without changing the attached browser session. ' +
1200
+ 'Filters status and intent on the server; source is case-insensitive and scans up to 1000 rows before applying limit. ' +
1201
+ 'Returns recordingsScanned and recordingsTruncatedByScan to disclose incomplete source searches.',
1202
+ inputSchema: recordingsListSchema.shape,
1203
+ annotations: { readOnlyHint: true },
1204
+ }, async (args) => pageCacheToolResult(async () => {
1205
+ const client = c();
1206
+ if (!client.listRecordings) {
1207
+ throw new Error('recordings_list is unavailable for this client. Switch to cloud mode with THINKRUN_BASE_URL and THINKRUN_API_KEY configured.');
1208
+ }
1209
+ return client.listRecordings(args);
1210
+ }));
1055
1211
  server.registerTool('page_cache_html', {
1056
1212
  title: 'Page cache — HTML',
1057
1213
  description: 'Stateless: fetch rendered HTML for a URL without a browser session (no sessionId). ' +
@@ -1294,6 +1450,16 @@ export function createServer(client, options) {
1294
1450
  }],
1295
1451
  };
1296
1452
  });
1453
+ server.registerTool('batch_actions', {
1454
+ title: 'Run Several Browser Actions',
1455
+ description: 'Run several browser actions in one call to save tool calls. Every step is checked first, and the first failure stops the rest. ' +
1456
+ 'Actions and fields: navigate (url), click/hover (selector), fill/select (selector, value), type (selector, text), press (key), ' +
1457
+ 'wait (selector or ms), wait_for_text (text), evaluate (script). Check the result before relying on later page state.',
1458
+ inputSchema: {
1459
+ sessionId: defaultableSessionIdSchema,
1460
+ steps: z.array(z.object({ action: z.enum(BATCH_ACTIONS) }).passthrough()).min(1).max(MAX_BATCH_STEPS),
1461
+ },
1462
+ }, (args) => handleBatchActions(c(), args, () => sid(args)));
1297
1463
  server.registerTool('press_key', {
1298
1464
  title: 'Press Keyboard Key',
1299
1465
  description: 'Press a keyboard key. Common keys: Enter, Tab, Escape, ArrowDown, ArrowUp, Backspace.',
@@ -1582,31 +1748,12 @@ export function createServer(client, options) {
1582
1748
  });
1583
1749
  server.registerTool('tab_new', {
1584
1750
  title: 'Open New Tab',
1585
- description: 'Open a new browser tab, optionally navigating to a URL. Local mode only.',
1751
+ description: 'Open a new browser tab, optionally navigating to a URL. It becomes the default session if none is set. Local mode only.',
1586
1752
  inputSchema: {
1587
1753
  sessionId: defaultableSessionIdSchema,
1588
1754
  url: z.string().optional().describe('URL to open in the new tab'),
1589
1755
  },
1590
- }, async (args) => {
1591
- try {
1592
- const result = await c().newTab(args.sessionId ?? sessionStateRef.current ?? '', args.url);
1593
- return {
1594
- content: [{
1595
- type: 'text',
1596
- text: JSON.stringify(result, null, 2),
1597
- }],
1598
- };
1599
- }
1600
- catch (error) {
1601
- return {
1602
- content: [{
1603
- type: 'text',
1604
- text: JSON.stringify({ success: false, error: String(error) }),
1605
- }],
1606
- isError: true,
1607
- };
1608
- }
1609
- });
1756
+ }, (args) => handleTabNew(c(), args, sessionStateRef));
1610
1757
  server.registerTool('tab_close', {
1611
1758
  title: 'Close Browser Tab',
1612
1759
  description: 'Close a browser tab by ID. If no tabId is provided, closes the current tab. Local mode only.',
@@ -1614,16 +1761,7 @@ export function createServer(client, options) {
1614
1761
  sessionId: defaultableSessionIdSchema,
1615
1762
  tabId: z.number().int().positive().optional().describe('Tab ID to close (default: current tab)'),
1616
1763
  },
1617
- }, async (args) => {
1618
- const result = await c().closeTab(sid(args), args.tabId);
1619
- return {
1620
- content: [{
1621
- type: 'text',
1622
- text: JSON.stringify(result, null, 2),
1623
- }],
1624
- isError: !result.success,
1625
- };
1626
- });
1764
+ }, (args) => handleTabClose(c(), args, sid(args), sessionStateRef));
1627
1765
  server.registerTool('tab_attach', {
1628
1766
  title: 'Attach To Existing Browser Tab',
1629
1767
  description: 'Attach to an existing local Chrome tab by tab ID and make it the default session. Local mode only.',
@@ -1654,7 +1792,7 @@ export function createServer(client, options) {
1654
1792
  }, (args) => handleWindowNew(c(), args, sessionStateRef));
1655
1793
  server.registerTool('session_release', {
1656
1794
  title: 'Release Local Session Ownership',
1657
- description: 'Release the current local tab ownership without closing the tab. Clears the default session when releasing the bound local session. Local mode only.',
1795
+ description: 'Complete the saved audit, if any, and release the current local tab ownership without closing the tab. Clears the default session when releasing the bound local session. Local mode only.',
1658
1796
  inputSchema: {
1659
1797
  sessionId: z.string().optional().describe('Optional session ID to release (defaults to the current bound local session)'),
1660
1798
  },
@@ -1912,6 +2050,7 @@ export function createServer(client, options) {
1912
2050
  isError: !result.success,
1913
2051
  };
1914
2052
  });
2053
+ applyToolVisibility(options?.resolvedMode);
1915
2054
  return server;
1916
2055
  }
1917
2056
  //# sourceMappingURL=server.js.map