Skip to content

Commit 69c98e8

Browse files
authored
refactor: dedupe and modularize runtime, OAuth, and CLI internals (#249)
* refactor: deduplicate pure utilities and remove dead internals * refactor(cli): centralize shared command and presentation contracts * refactor(oauth): separate persistence stores from refresh policy * refactor(runtime): isolate connection cache and transport ownership
1 parent 7259c8c commit 69c98e8

65 files changed

Lines changed: 2977 additions & 2990 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/chrome-devtools-auto-connect-patch.ts‎

Lines changed: 51 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,41 +31,83 @@ const PATCHED_DETECTION_BLOCK = `if (await mcporterWithTimeout(page.hasDevTools(
3131
mcpPage.devToolsPage = await mcporterWithTimeout(page.openDevTools(), undefined);
3232
}`;
3333

34+
interface PatchFileSystem {
35+
realpathSync(filePath: string): string;
36+
readFileSync(filePath: string, encoding: 'utf8'): string;
37+
writeFileSync(filePath: string, contents: string): void;
38+
}
39+
40+
interface PatchPath {
41+
dirname(filePath: string): string;
42+
join(...paths: string[]): string;
43+
resolve(...paths: string[]): string;
44+
}
45+
3446
patchChromeDevtoolsMcp();
3547

3648
export function patchChromeDevtoolsMcp(mainPath = process.argv[1]): void {
49+
patchChromeDevtoolsMcpWithDependencies(mainPath, fs, path, MARKER, HELPER, DETECTION_BLOCK, PATCHED_DETECTION_BLOCK);
50+
}
51+
52+
export function renderChromeDevtoolsAutoConnectPatchSource(): string {
53+
return `import fs from 'node:fs';
54+
import path from 'node:path';
55+
56+
const patchChromeDevtoolsMcp = ${patchChromeDevtoolsMcpWithDependencies.toString()};
57+
58+
patchChromeDevtoolsMcp(
59+
process.argv[1],
60+
fs,
61+
path,
62+
${JSON.stringify(MARKER)},
63+
${JSON.stringify(HELPER)},
64+
${JSON.stringify(DETECTION_BLOCK)},
65+
${JSON.stringify(PATCHED_DETECTION_BLOCK)}
66+
);
67+
`;
68+
}
69+
70+
function patchChromeDevtoolsMcpWithDependencies(
71+
mainPath: string | undefined,
72+
fsApi: PatchFileSystem,
73+
pathApi: PatchPath,
74+
marker: string,
75+
helper: string,
76+
detectionBlock: string,
77+
patchedDetectionBlock: string
78+
): void {
3779
if (!mainPath || !mainPath.includes('chrome-devtools-mcp')) {
3880
return;
3981
}
4082
let resolvedMainPath: string;
4183
try {
42-
resolvedMainPath = fs.realpathSync(mainPath);
84+
resolvedMainPath = fsApi.realpathSync(mainPath);
4385
} catch {
4486
return;
4587
}
46-
if (!resolvedMainPath.endsWith(path.join('bin', 'chrome-devtools-mcp.js'))) {
88+
if (!resolvedMainPath.endsWith(pathApi.join('bin', 'chrome-devtools-mcp.js'))) {
4789
return;
4890
}
49-
const contextPath = path.resolve(path.dirname(resolvedMainPath), '..', 'McpContext.js');
91+
const contextPath = pathApi.resolve(pathApi.dirname(resolvedMainPath), '..', 'McpContext.js');
5092
let source: string;
5193
try {
52-
source = fs.readFileSync(contextPath, 'utf8');
94+
source = fsApi.readFileSync(contextPath, 'utf8');
5395
} catch {
5496
return;
5597
}
56-
if (source.includes(MARKER)) {
98+
if (source.includes(marker)) {
5799
return;
58100
}
59-
if (!source.includes(DETECTION_BLOCK)) {
101+
if (!source.includes(detectionBlock)) {
60102
return;
61103
}
62104
const withHelper = source.replace(
63105
'const NAVIGATION_TIMEOUT = 10_000;\n',
64-
`const NAVIGATION_TIMEOUT = 10_000;\n${HELPER}`
106+
`const NAVIGATION_TIMEOUT = 10_000;\n${helper}`
65107
);
66-
const patched = withHelper.replace(DETECTION_BLOCK, PATCHED_DETECTION_BLOCK);
108+
const patched = withHelper.replace(detectionBlock, patchedDetectionBlock);
67109
try {
68-
fs.writeFileSync(contextPath, patched);
110+
fsApi.writeFileSync(contextPath, patched);
69111
} catch {
70112
return;
71113
}

‎src/chrome-devtools-compat.ts‎

Lines changed: 2 additions & 74 deletions
Original file line numberDiff line numberDiff line change
@@ -2,82 +2,10 @@ import fs from 'node:fs';
22
import os from 'node:os';
33
import path from 'node:path';
44
import { fileURLToPath, pathToFileURL } from 'node:url';
5+
import { renderChromeDevtoolsAutoConnectPatchSource } from './chrome-devtools-auto-connect-patch.js';
56

67
const AUTO_CONNECT_FLAGS = new Set(['--autoConnect', '--auto-connect']);
78
const FALLBACK_PATCH_FILENAME = 'mcporter-chrome-devtools-auto-connect-patch.js';
8-
const FALLBACK_PATCH_SOURCE = `import fs from 'node:fs';
9-
import path from 'node:path';
10-
11-
const MARKER = 'MCPORTER_DEVTOOLS_TIMEOUT_PATCH';
12-
const HELPER = \`// \${MARKER}
13-
const MCPORTER_DEVTOOLS_DETECTION_TIMEOUT = 1_000;
14-
async function mcporterWithTimeout(promise, fallback) {
15-
let timer;
16-
try {
17-
return await Promise.race([
18-
promise,
19-
new Promise(resolve => {
20-
timer = setTimeout(resolve, MCPORTER_DEVTOOLS_DETECTION_TIMEOUT, fallback);
21-
timer.unref?.();
22-
}),
23-
]);
24-
}
25-
finally {
26-
if (timer) {
27-
clearTimeout(timer);
28-
}
29-
}
30-
}
31-
\`;
32-
33-
const DETECTION_BLOCK = \`if (await page.hasDevTools()) {
34-
mcpPage.devToolsPage = await page.openDevTools();
35-
}\`;
36-
37-
const PATCHED_DETECTION_BLOCK = \`if (await mcporterWithTimeout(page.hasDevTools(), false)) {
38-
mcpPage.devToolsPage = await mcporterWithTimeout(page.openDevTools(), undefined);
39-
}\`;
40-
41-
patchChromeDevtoolsMcp();
42-
43-
function patchChromeDevtoolsMcp(mainPath = process.argv[1]) {
44-
if (!mainPath || !mainPath.includes('chrome-devtools-mcp')) {
45-
return;
46-
}
47-
let resolvedMainPath;
48-
try {
49-
resolvedMainPath = fs.realpathSync(mainPath);
50-
} catch {
51-
return;
52-
}
53-
if (!resolvedMainPath.endsWith(path.join('bin', 'chrome-devtools-mcp.js'))) {
54-
return;
55-
}
56-
const contextPath = path.resolve(path.dirname(resolvedMainPath), '..', 'McpContext.js');
57-
let source;
58-
try {
59-
source = fs.readFileSync(contextPath, 'utf8');
60-
} catch {
61-
return;
62-
}
63-
if (source.includes(MARKER)) {
64-
return;
65-
}
66-
if (!source.includes(DETECTION_BLOCK)) {
67-
return;
68-
}
69-
const withHelper = source.replace(
70-
'const NAVIGATION_TIMEOUT = 10_000;\\n',
71-
\`const NAVIGATION_TIMEOUT = 10_000;\\n\${HELPER}\`
72-
);
73-
const patched = withHelper.replace(DETECTION_BLOCK, PATCHED_DETECTION_BLOCK);
74-
try {
75-
fs.writeFileSync(contextPath, patched);
76-
} catch {
77-
return;
78-
}
79-
}
80-
`;
819

8210
export interface ChromeDevtoolsCompatResult {
8311
readonly env: Record<string, string>;
@@ -154,7 +82,7 @@ function defaultChromeDevtoolsPatchCandidates(): string[] {
15482
function writeFallbackPatch(fallbackDir: string): string | undefined {
15583
const patchPath = path.join(fallbackDir, FALLBACK_PATCH_FILENAME);
15684
try {
157-
fs.writeFileSync(patchPath, FALLBACK_PATCH_SOURCE, { mode: 0o600 });
85+
fs.writeFileSync(patchPath, renderChromeDevtoolsAutoConnectPatchSource(), { mode: 0o600 });
15886
return patchPath;
15987
} catch {
16088
return undefined;

‎src/cli-metadata.ts‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { spawn } from 'node:child_process';
22
import fs from 'node:fs/promises';
33
import type { ServerDefinition, ServerSource } from './config.js';
4+
import { pickSharedDefinitionFields } from './definition-fields.js';
45

56
export type CliArtifactKind = 'template' | 'bundle' | 'binary';
67

@@ -145,6 +146,7 @@ function isErrno(error: unknown, code: string): error is NodeJS.ErrnoException {
145146

146147
// serializeDefinition converts an in-memory server definition into the metadata-friendly JSON form.
147148
export function serializeDefinition(definition: ServerDefinition): SerializedServerDefinition {
149+
const sharedFields = pickSharedDefinitionFields(definition);
148150
if (definition.command.kind === 'http') {
149151
return {
150152
name: definition.name,
@@ -155,18 +157,7 @@ export function serializeDefinition(definition: ServerDefinition): SerializedSer
155157
headers: definition.command.headers,
156158
},
157159
env: definition.env,
158-
auth: definition.auth,
159-
tokenCacheDir: definition.tokenCacheDir,
160-
clientName: definition.clientName,
161-
oauthClientId: definition.oauthClientId,
162-
oauthClientSecretEnv: definition.oauthClientSecretEnv,
163-
oauthTokenEndpointAuthMethod: definition.oauthTokenEndpointAuthMethod,
164-
oauthRedirectUrl: definition.oauthRedirectUrl,
165-
oauthScope: definition.oauthScope,
166-
refresh: definition.refresh,
167-
httpFetch: definition.httpFetch,
168-
allowedTools: definition.allowedTools,
169-
blockedTools: definition.blockedTools,
160+
...sharedFields,
170161
};
171162
}
172163
return {
@@ -179,17 +170,6 @@ export function serializeDefinition(definition: ServerDefinition): SerializedSer
179170
cwd: definition.command.cwd,
180171
},
181172
env: definition.env,
182-
auth: definition.auth,
183-
tokenCacheDir: definition.tokenCacheDir,
184-
clientName: definition.clientName,
185-
oauthClientId: definition.oauthClientId,
186-
oauthClientSecretEnv: definition.oauthClientSecretEnv,
187-
oauthTokenEndpointAuthMethod: definition.oauthTokenEndpointAuthMethod,
188-
oauthRedirectUrl: definition.oauthRedirectUrl,
189-
oauthScope: definition.oauthScope,
190-
refresh: definition.refresh,
191-
httpFetch: definition.httpFetch,
192-
allowedTools: definition.allowedTools,
193-
blockedTools: definition.blockedTools,
173+
...sharedFields,
194174
};
195175
}

‎src/cli/adhoc-help.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
export const ADHOC_SERVER_HELP_ENTRIES = [
2+
{ flag: '--http-url <url>', description: 'Register an HTTP server for this run.' },
3+
{ flag: '--allow-http', description: 'Permit plain http:// URLs with --http-url.' },
4+
{ flag: '--header KEY=value', description: 'Attach HTTP headers (repeatable).' },
5+
{ flag: '--stdio <command>', description: 'Run a stdio MCP server (repeat --stdio-arg for args).' },
6+
{ flag: '--stdio-arg <value>', description: 'Append args to the stdio command (repeatable).' },
7+
{ flag: '--env KEY=value', description: 'Inject env vars for stdio servers (repeatable).' },
8+
{ flag: '--cwd <path>', description: 'Working directory for stdio servers.' },
9+
{ flag: '--name <value>', description: 'Override the display name for ad-hoc servers.' },
10+
{ flag: '--description <text>', description: 'Override the description for ad-hoc servers.' },
11+
{ flag: '--persist <path>', description: 'Write the ad-hoc definition to config/mcporter.json.' },
12+
{ flag: '--yes', description: 'Skip confirmation prompts when persisting.' },
13+
] as const;
14+
15+
export function renderAdhocServerHelpLines(width = 23): string[] {
16+
return ADHOC_SERVER_HELP_ENTRIES.map((entry) => ` ${entry.flag.padEnd(width)}${entry.description}`);
17+
}

‎src/cli/auth-command.ts‎

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import type { ServerDefinition } from '../config-schema.js';
33
import type { OAuthAuthorizationRequest, OAuthSessionOptions } from '../oauth.js';
44
import { analyzeConnectionError } from '../error-classifier.js';
55
import { clearOAuthCaches } from '../oauth-persistence.js';
6-
import type { createRuntime } from '../runtime.js';
6+
import type { Runtime } from '../runtime.js';
77
import { isOAuthFlowError } from '../runtime/oauth.js';
8+
import { renderAdhocServerHelpLines } from './adhoc-help.js';
89
import type { EphemeralServerSpec } from './adhoc-server.js';
910
import { extractEphemeralServerFlags } from './ephemeral-flags.js';
1011
import { persistPreparedEphemeralServer, prepareEphemeralServerTarget } from './ephemeral-target.js';
@@ -13,8 +14,6 @@ import { buildConnectionIssueEnvelope } from './json-output.js';
1314
import { getActiveLogger, logInfo, logWarn } from './logger-context.js';
1415
import { consumeOutputFormat } from './output-format.js';
1516

16-
type Runtime = Awaited<ReturnType<typeof createRuntime>>;
17-
1817
type BrowserSuppression = 'default' | 'no-browser';
1918

2019
const TRUE_VALUES = new Set(['1', 'true', 'yes']);
@@ -244,17 +243,7 @@ export function printAuthHelp(): void {
244243
' MCPORTER_OAUTH_NO_BROWSER=1|true|yes also enables --no-browser behavior.',
245244
'',
246245
'Ad-hoc targets:',
247-
' --http-url <url> Register an HTTP server for this run.',
248-
' --allow-http Permit plain http:// URLs with --http-url.',
249-
' --header KEY=value Attach HTTP headers (repeatable).',
250-
' --stdio <command> Run a stdio MCP server (repeat --stdio-arg for args).',
251-
' --stdio-arg <value> Append args to the stdio command (repeatable).',
252-
' --env KEY=value Inject env vars for stdio servers (repeatable).',
253-
' --cwd <path> Working directory for stdio servers.',
254-
' --name <value> Override the display name for ad-hoc servers.',
255-
' --description <text> Override the description for ad-hoc servers.',
256-
' --persist <path> Write the ad-hoc definition to config/mcporter.json.',
257-
' --yes Skip confirmation prompts when persisting.',
246+
...renderAdhocServerHelpLines(24),
258247
'',
259248
'Examples:',
260249
' mcporter auth linear',

0 commit comments

Comments
 (0)