Skip to content

Commit 755026c

Browse files
fixed json
1 parent 01c3abb commit 755026c

File tree

1 file changed

+72
-52
lines changed

1 file changed

+72
-52
lines changed

stagehand/src/index.ts

Lines changed: 72 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ const stagehandConfig: ConstructorParams = {
5353
debugDom: true /* Enable DOM debugging features */,
5454
headless: false /* Run browser in headless mode */,
5555
logger: (message: LogLine) =>
56-
console.log(logLineToString(message)) /* Custom logging function */,
56+
console.error(logLineToString(message)) /* Custom logging function to stderr */,
5757
domSettleTimeoutMs: 30_000 /* Timeout for DOM to settle in milliseconds */,
5858
browserbaseSessionCreateParams: {
5959
projectId: process.env.BROWSERBASE_PROJECT_ID!,
@@ -209,50 +209,59 @@ const TOOLS: Tool[] = [
209209

210210
// Global state
211211
let stagehand: Stagehand | undefined;
212+
let serverInstance: Server | undefined;
212213
const consoleLogs: string[] = [];
213214
const operationLogs: string[] = [];
214215

215216
function log(message: string, level: 'info' | 'error' | 'debug' = 'info') {
216-
const timestamp = new Date().toISOString();
217-
const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
218-
operationLogs.push(logMessage);
217+
// const timestamp = new Date().toISOString();
218+
// const logMessage = `[${timestamp}] [${level.toUpperCase()}] ${message}`;
219+
// operationLogs.push(logMessage);
219220

220-
// Write to file
221-
fs.appendFileSync(LOG_FILE, logMessage + '\n');
221+
// // Write to file
222+
// fs.appendFileSync(LOG_FILE, logMessage + '\n');
222223

223-
// Console output if debug is enabled
224-
if (process.env.DEBUG || level === 'error') {
225-
console.error(logMessage);
226-
}
224+
// // Console output to stderr
225+
// if (process.env.DEBUG || level === 'error') {
226+
// console.error(logMessage);
227+
// }
228+
229+
// // Send logging message to client for important events
230+
// if (serverInstance && (level === 'info' || level === 'error')) {
231+
// serverInstance.sendLoggingMessage({
232+
// level: level,
233+
// data: message,
234+
// });
235+
// }
227236
}
228237

229238
function logRequest(type: string, params: any) {
230-
const requestLog = {
231-
timestamp: new Date().toISOString(),
232-
type,
233-
params,
234-
};
235-
log(`REQUEST: ${JSON.stringify(requestLog, null, 2)}`, 'debug');
239+
// const requestLog = {
240+
// timestamp: new Date().toISOString(),
241+
// type,
242+
// params,
243+
// };
244+
// log(`REQUEST: ${JSON.stringify(requestLog, null, 2)}`, 'debug');
236245
}
237246

238247
function logResponse(type: string, response: any) {
239-
const responseLog = {
240-
timestamp: new Date().toISOString(),
241-
type,
242-
response,
243-
};
244-
log(`RESPONSE: ${JSON.stringify(responseLog, null, 2)}`, 'debug');
248+
// const responseLog = {
249+
// timestamp: new Date().toISOString(),
250+
// type,
251+
// response,
252+
// };
253+
// log(`RESPONSE: ${JSON.stringify(responseLog, null, 2)}`, 'debug');
245254
}
246255

247256
// Ensure Stagehand is initialized
248257
async function ensureStagehand() {
249-
log("Ensuring Stagehand is initialized...");
258+
// log("Ensuring Stagehand is initialized...");
250259
if (!stagehand) {
251-
log("Initializing Stagehand...");
260+
// log("Initializing Stagehand...");
252261
stagehand = new Stagehand(stagehandConfig);
253-
log("Running init()");
262+
// log("Running init()");
254263
await stagehand.init();
255-
log("Stagehand initialized successfully");
264+
// log("Stagehand initialized successfully");
256265
}
257266
return stagehand;
258267
}
@@ -277,7 +286,7 @@ function sanitizeMessage(message: any): string {
277286
}
278287
return JSON.stringify(message);
279288
} catch (error) {
280-
log(`Invalid message format: ${error}`, 'error');
289+
// log(`Invalid message format: ${error}`, 'error');
281290
return JSON.stringify({
282291
jsonrpc: '2.0',
283292
error: {
@@ -294,13 +303,13 @@ async function handleToolCall(
294303
name: string,
295304
args: any
296305
): Promise<CallToolResult> {
297-
log(`Handling tool call: ${name} with args: ${JSON.stringify(args)}`);
306+
// log(`Handling tool call: ${name} with args: ${JSON.stringify(args)}`, 'info');
298307

299308
try {
300309
stagehand = await ensureStagehand();
301310
} catch (error) {
302311
const errorMsg = error instanceof Error ? error.message : String(error);
303-
log(`Failed to initialize Stagehand: ${errorMsg}`, 'error');
312+
// log(`Failed to initialize Stagehand: ${errorMsg}`, 'error');
304313
return {
305314
content: [
306315
{
@@ -315,13 +324,17 @@ async function handleToolCall(
315324
isError: true,
316325
};
317326
}
327+
// log(`Stagehand initialized successfully`);
328+
// log(`name: ${name}`);
329+
// log(`args: ${JSON.stringify(args)}`);
330+
318331

319332
switch (name) {
320333
case "stagehand_navigate":
321334
try {
322-
log(`Navigating to URL: ${args.url}`);
335+
// log(`Navigating to URL: ${args.url}`, 'info');
323336
await stagehand.page.goto(args.url);
324-
log("Navigation successful");
337+
// log("Navigation successful", 'info');
325338
return {
326339
content: [
327340
{
@@ -333,7 +346,7 @@ async function handleToolCall(
333346
};
334347
} catch (error) {
335348
const errorMsg = error instanceof Error ? error.message : String(error);
336-
log(`Navigation failed: ${errorMsg}`);
349+
// log(`Navigation failed: ${errorMsg}`, 'error');
337350
return {
338351
content: [
339352
{
@@ -351,12 +364,12 @@ async function handleToolCall(
351364

352365
case "stagehand_act":
353366
try {
354-
log(`Performing action: ${args.action}`);
367+
// log(`Performing action: ${args.action}`, 'info');
355368
await stagehand.page.act({
356369
action: args.action,
357370
variables: args.variables,
358371
});
359-
log("Action completed successfully");
372+
// log("Action completed successfully", 'info');
360373
return {
361374
content: [
362375
{
@@ -368,7 +381,7 @@ async function handleToolCall(
368381
};
369382
} catch (error) {
370383
const errorMsg = error instanceof Error ? error.message : String(error);
371-
log(`Action failed: ${errorMsg}`);
384+
// log(`Action failed: ${errorMsg}`, 'error');
372385
return {
373386
content: [
374387
{
@@ -386,8 +399,8 @@ async function handleToolCall(
386399

387400
case "stagehand_extract":
388401
try {
389-
log(`Extracting data with instruction: ${args.instruction}`);
390-
log(`Schema: ${JSON.stringify(args.schema)}`);
402+
// log(`Extracting data with instruction: ${args.instruction}`, 'info');
403+
// log(`Schema: ${JSON.stringify(args.schema)}`, 'debug');
391404
// Convert the JSON schema from args.schema to a zod schema
392405
const zodSchema = jsonSchemaToZod(args.schema) as AnyZodObject;
393406
const data = await stagehand.extract({
@@ -398,7 +411,7 @@ async function handleToolCall(
398411
throw new Error("Invalid extraction response format");
399412
}
400413
const extractedData = data.data;
401-
log(`Data extracted successfully: ${JSON.stringify(extractedData)}`);
414+
// log(`Data extracted successfully: ${JSON.stringify(extractedData)}`, 'info');
402415
return {
403416
content: [
404417
{
@@ -414,7 +427,7 @@ async function handleToolCall(
414427
};
415428
} catch (error) {
416429
const errorMsg = error instanceof Error ? error.message : String(error);
417-
log(`Extraction failed: ${errorMsg}`);
430+
// log(`Extraction failed: ${errorMsg}`, 'error');
418431
return {
419432
content: [
420433
{
@@ -431,13 +444,13 @@ async function handleToolCall(
431444
}
432445
case "stagehand_observe":
433446
try {
434-
log(`Starting observation with instruction: ${args.instruction}`);
447+
// log(`Starting observation with instruction: ${args.instruction}`, 'info');
435448
const observations = await stagehand.page.observe({
436449
instruction: args.instruction,
437450
});
438-
log(
439-
`Observation completed successfully: ${JSON.stringify(observations)}`
440-
);
451+
// log(
452+
// `Observation completed successfully: ${JSON.stringify(observations)}`, 'info'
453+
// );
441454
return {
442455
content: [
443456
{
@@ -449,7 +462,7 @@ async function handleToolCall(
449462
};
450463
} catch (error) {
451464
const errorMsg = error instanceof Error ? error.message : String(error);
452-
log(`Observation failed: ${errorMsg}`);
465+
// log(`Observation failed: ${errorMsg}`, 'error');
453466
return {
454467
content: [
455468
{
@@ -466,7 +479,7 @@ async function handleToolCall(
466479
}
467480

468481
default:
469-
log(`Unknown tool called: ${name}`);
482+
// log(`Unknown tool called: ${name}`, 'error');
470483
return {
471484
content: [
472485
{
@@ -497,6 +510,9 @@ const server = new Server(
497510
}
498511
);
499512

513+
// Store server instance for logging
514+
serverInstance = server;
515+
500516
// Setup request handlers
501517
server.setRequestHandler(ListToolsRequestSchema, async (request) => {
502518
try {
@@ -507,7 +523,7 @@ server.setRequestHandler(ListToolsRequestSchema, async (request) => {
507523
return JSON.parse(sanitizedResponse);
508524
} catch (error) {
509525
const errorMsg = error instanceof Error ? error.message : String(error);
510-
log(`ListTools handler error: ${errorMsg}`, 'error');
526+
// log(`ListTools handler error: ${errorMsg}`, 'error');
511527
return {
512528
error: {
513529
code: -32603,
@@ -536,7 +552,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
536552
return JSON.parse(sanitizedResult);
537553
} catch (error) {
538554
const errorMsg = error instanceof Error ? error.message : String(error);
539-
log(`CallTool handler error: ${errorMsg}`, 'error');
555+
// log(`CallTool handler error: ${errorMsg}`, 'error');
540556
return {
541557
error: {
542558
code: -32603,
@@ -557,7 +573,7 @@ server.setRequestHandler(ListResourcesRequestSchema, async (request) => {
557573
return JSON.parse(sanitizedResponse);
558574
} catch (error) {
559575
const errorMsg = error instanceof Error ? error.message : String(error);
560-
log(`ListResources handler error: ${errorMsg}`, 'error');
576+
// log(`ListResources handler error: ${errorMsg}`, 'error');
561577
return {
562578
error: {
563579
code: -32603,
@@ -577,7 +593,7 @@ server.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) =>
577593
return JSON.parse(sanitizedResponse);
578594
} catch (error) {
579595
const errorMsg = error instanceof Error ? error.message : String(error);
580-
log(`ListResourceTemplates handler error: ${errorMsg}`, 'error');
596+
// log(`ListResourceTemplates handler error: ${errorMsg}`, 'error');
581597
return {
582598
error: {
583599
code: -32603,
@@ -589,14 +605,18 @@ server.setRequestHandler(ListResourceTemplatesRequestSchema, async (request) =>
589605

590606
// Run the server
591607
async function runServer() {
592-
log("Starting Stagehand MCP server...", 'info');
608+
// log("Starting Stagehand MCP server...", 'info');
593609
const transport = new StdioServerTransport();
594610
await server.connect(transport);
595-
log("Server started successfully", 'info');
611+
// log("Server started successfully", 'info');
612+
server.sendLoggingMessage({
613+
level: "info",
614+
data: "Stagehand MCP server is ready to accept requests",
615+
});
596616
}
597617

598618
runServer().catch((error) => {
599619
const errorMsg = error instanceof Error ? error.message : String(error);
600-
log(`Server error: ${errorMsg}`, 'error');
620+
// log(`Server error: ${errorMsg}`, 'error');
601621
console.error(error);
602622
});

0 commit comments

Comments
 (0)