scrapeless-mcp-server
Version:
Scrapeless Mcp Server
121 lines (120 loc) • 4.02 kB
JavaScript
import { SessionManager } from "./session-manager.js";
import { uuid } from "./tools/utils.js";
export class Context {
sessionManager;
currentSessionId = "default-session-id";
apiKey;
constructor(apiKey) {
this.sessionManager = SessionManager.getInstance();
this.apiKey = apiKey;
}
getSession(id) {
return this.sessionManager.getSession(`${id ?? this.currentSessionId}-${this.apiKey}`);
}
async run(tool, params, headers) {
if (!this.apiKey) {
return {
content: [
{
type: "text",
text: `API key is missing.`,
},
],
};
}
if (params.sessionId && params.sessionId !== this.currentSessionId) {
this.currentSessionId = params.sessionId;
}
const toolName = tool.name;
if (toolName === "browser_create") {
const newSessionId = uuid();
try {
await this.sessionManager.createSession(`${newSessionId}-${this.apiKey}`, this.apiKey, headers);
return {
content: [
{
type: "text",
text: `New browser session created with ID: ${newSessionId}`,
},
],
};
}
catch (error) {
return {
content: [
{
type: "text",
text: `Failed to create browser session. Please try again later.`,
},
],
};
}
}
if (toolName === "browser_close") {
const sessionId = params?.sessionId;
if (!sessionId) {
return {
content: [
{
type: "text",
text: `Session ID is missing.`,
},
],
};
}
try {
await this.sessionManager.closeSession(`${sessionId}-${this.apiKey}`);
return {
content: [
{
type: "text",
text: `Browser session with ID: ${sessionId} has been closed.`,
},
],
};
}
catch (error) {
return {
content: [
{
type: "text",
text: `Failed to close browser session with ID: ${sessionId}. Please try again later.`,
},
],
};
}
}
let session = null;
session = this.sessionManager.getSession(`${this.currentSessionId}-${this.apiKey}`);
if (!session) {
const newSessionId = uuid();
await this.sessionManager.createSession(`${newSessionId}-${this.apiKey}`, this.apiKey);
this.currentSessionId = newSessionId;
}
let toolActionOutput = undefined;
let actionSucceeded = false;
try {
let action = undefined;
action = tool.handle;
if (action) {
toolActionOutput = await action(this, params);
actionSucceeded = true;
}
}
catch (e) {
}
finally {
if (actionSucceeded && toolActionOutput !== undefined) {
return toolActionOutput;
}
return {
content: [
{
type: "text",
text: `${toolName} action completed successfully.`,
},
],
};
}
}
}