# Directory Structure ``` ├── .gitignore ├── .prettierrc ├── .prettierrc.json ├── build.js ├── package-lock.json ├── package.json ├── screenshots │ └── .gitkeep ├── src │ ├── constants.ts │ ├── helpers.ts │ └── index.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /screenshots/.gitkeep: -------------------------------------------------------------------------------- ``` 1 | ``` -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` 1 | node_modules 2 | 3 | build/ 4 | 5 | screenshots/*.png 6 | 7 | 8 | .env ``` -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- ``` 1 | { 2 | "printWidth": 140, 3 | "singleQuote": true, 4 | "semi": true, 5 | "useTabs": true 6 | } 7 | ``` -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 4, 4 | "semi": false, 5 | "singleQuote": true, 6 | "printWidth": 120, 7 | "arrowParens": "avoid" 8 | } 9 | ``` -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- ```typescript 1 | export const USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Mobile/15E148 Safari/604.1'; ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "name": "mcp-playwright-screenshot", 3 | "version": "1.0.0", 4 | "main": "index.js", 5 | "type": "module", 6 | "bin": { 7 | "playwright-screenshot": "./build/index.js" 8 | }, 9 | "files": [ 10 | "build" 11 | ], 12 | "scripts": { 13 | "build": "tsc && chmod 755 build/index.js", 14 | "esbuild": "node build.js", 15 | "test": "echo \"Error: no test specified\" && exit 1", 16 | "prettierformat": "prettier --write", 17 | "prettierall": "prettier --write .", 18 | "lint-staged": "lint-staged" 19 | }, 20 | "precommit": "lint-staged", 21 | "lint-staged": { 22 | "./**/*.{js,jsx,ts,tsx}": [ 23 | "npm run prettierformat", 24 | "git add ." 25 | ] 26 | }, 27 | "keywords": [], 28 | "author": "", 29 | "license": "ISC", 30 | "description": "", 31 | "dependencies": { 32 | "@modelcontextprotocol/sdk": "^1.7.0", 33 | "playwright": "^1.51.1", 34 | "zod": "^3.24.2" 35 | }, 36 | "devDependencies": { 37 | "@types/node": "^22.13.13", 38 | "esbuild": "^0.25.1", 39 | "lint-staged": "^15.5.0", 40 | "pre-commit": "^1.2.2", 41 | "prettier": "^3.5.3", 42 | "typescript": "^5.8.2" 43 | } 44 | } 45 | ``` -------------------------------------------------------------------------------- /src/helpers.ts: -------------------------------------------------------------------------------- ```typescript 1 | // Helper function for making NWS API requests 2 | import { USER_AGENT } from "./constants.js"; 3 | export async function makeNWSRequest<T>(url: string): Promise<T | null> { 4 | const headers = { 5 | "User-Agent": USER_AGENT, 6 | Accept: "application/geo+json", 7 | }; 8 | 9 | try { 10 | const response = await fetch(url, { headers }); 11 | if (!response.ok) { 12 | throw new Error(`HTTP error! status: ${response.status}`); 13 | } 14 | return (await response.json()) as T; 15 | } catch (error) { 16 | console.error("Error making NWS request:", error); 17 | return null; 18 | } 19 | } 20 | 21 | export interface AlertFeature { 22 | properties: { 23 | event?: string; 24 | areaDesc?: string; 25 | severity?: string; 26 | status?: string; 27 | headline?: string; 28 | }; 29 | } 30 | 31 | // Format alert data 32 | export function formatAlert(feature: AlertFeature): string { 33 | const props = feature.properties; 34 | return [ 35 | `Event: ${props.event || "Unknown"}`, 36 | `Area: ${props.areaDesc || "Unknown"}`, 37 | `Severity: ${props.severity || "Unknown"}`, 38 | `Status: ${props.status || "Unknown"}`, 39 | `Headline: ${props.headline || "No headline"}`, 40 | "---", 41 | ].join("\n"); 42 | } 43 | 44 | export interface ForecastPeriod { 45 | name?: string; 46 | temperature?: number; 47 | temperatureUnit?: string; 48 | windSpeed?: string; 49 | windDirection?: string; 50 | shortForecast?: string; 51 | } 52 | 53 | export interface AlertsResponse { 54 | features: AlertFeature[]; 55 | } 56 | 57 | export interface PointsResponse { 58 | properties: { 59 | forecast?: string; 60 | }; 61 | } 62 | 63 | export interface ForecastResponse { 64 | properties: { 65 | periods: ForecastPeriod[]; 66 | }; 67 | } ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | #!/usr/bin/env node 2 | 3 | import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; 4 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 5 | import { z } from 'zod'; 6 | import playwright from 'playwright'; 7 | import fs from 'fs' 8 | import path from 'path' 9 | 10 | const NWS_API_BASE = 'https://api.weather.gov'; 11 | 12 | // Create server instance 13 | const server = new McpServer({ 14 | name: 'playwright-screenshot', 15 | version: '1.0.0', 16 | capabilities: { 17 | resources: {}, 18 | tools: {}, 19 | }, 20 | }); 21 | 22 | server.tool( 23 | "get-screenshot", 24 | "Get a screenshot of a webpage", 25 | { 26 | url: z.string().url().describe("URL of the webpage to screenshot"), 27 | }, 28 | async ({ url }) => { 29 | // return { 30 | // content: [{ 31 | // type: "text", 32 | // text: "Hello, World!", 33 | // }] 34 | // } 35 | // const browser = await playwright.chromium.launch(); 36 | const token = process.env.LIGHTPANDA_TOKEN; 37 | const saveFolderPath = process.env.SAVE_FOLDER_PATH; 38 | if(!token){ 39 | return { 40 | content: [ 41 | { 42 | type: "text", 43 | text: "Please provide LIGHTPANDA_TOKEN in the environment variable", 44 | }, 45 | ], 46 | } 47 | } 48 | 49 | if(!saveFolderPath){ 50 | return { 51 | content: [ 52 | { 53 | type: "text", 54 | text: "Please provide SAVE_FOLDER_PATH in the environment variable", 55 | }, 56 | ], 57 | } 58 | } 59 | const browser = await playwright.chromium.connectOverCDP( 60 | `wss://cloud.lightpanda.io/ws?token=${token}`, 61 | ); 62 | const context = await browser.newContext(); 63 | const page = await context.newPage(); 64 | await page.goto(url); 65 | const screenshot = await page.screenshot(); 66 | const now = Date.now() 67 | 68 | const screenshotPath = path.join(saveFolderPath, `screenshot_${now}.png`); 69 | const dirPath = path.dirname(saveFolderPath); 70 | fs.mkdirSync(dirPath, { recursive: true }); // create folder if not exist 71 | // save screenshot to local 72 | fs.writeFileSync(screenshotPath, screenshot); 73 | // get the file path 74 | // const filePath = fs.realpathSync('screenshot.png'); 75 | 76 | await browser.close(); 77 | return { 78 | content: [ 79 | { 80 | type: "text", 81 | text: `the screenshot is saved to local folder, the path is: ${screenshotPath}` 82 | }, 83 | ], 84 | }; 85 | } 86 | ) 87 | 88 | 89 | async function main() { 90 | const transport = new StdioServerTransport(); 91 | await server.connect(transport); 92 | console.info('playwright screenshot MCP Server running on stdio'); 93 | } 94 | 95 | main().catch((error) => { 96 | console.error('Fatal error in main():', error); 97 | process.exit(1); 98 | }); 99 | ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig to read more about this file */ 4 | 5 | /* Projects */ 6 | // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "ES2022" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ 22 | // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ 26 | 27 | /* Modules */ 28 | "module": "Node16" /* Specify what module code is generated. */, 29 | "rootDir": "./src" /* Specify the root folder within your source files. */, 30 | "moduleResolution": "node16" /* Specify how TypeScript looks up a file from a given module specifier. */, 31 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 32 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 33 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 34 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ 35 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 36 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 37 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ 38 | // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */ 39 | // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */ 40 | // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */ 41 | // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */ 42 | // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */ 43 | // "noUncheckedSideEffectImports": true, /* Check side effect imports. */ 44 | // "resolveJsonModule": true, /* Enable importing .json files. */ 45 | // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ 46 | // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */ 47 | 48 | /* JavaScript Support */ 49 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ 50 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 51 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ 52 | 53 | /* Emit */ 54 | // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ 55 | // "declarationMap": true, /* Create sourcemaps for d.ts files. */ 56 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ 57 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "noEmit": true, /* Disable emitting files from a compilation. */ 60 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ 61 | "outDir": "./build" /* Specify an output folder for all emitted files. */, 62 | // "removeComments": true, /* Disable emitting comments. */ 63 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 64 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ 65 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 66 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 67 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 68 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 69 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 70 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ 71 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ 72 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 73 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ 74 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 75 | 76 | /* Interop Constraints */ 77 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 78 | // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */ 79 | // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */ 80 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 81 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */, 82 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 83 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 84 | 85 | /* Type Checking */ 86 | "strict": true /* Enable all strict type-checking options. */, 87 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ 88 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ 89 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 90 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ 91 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 92 | // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */ 93 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ 94 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ 95 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ 96 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ 97 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ 98 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 99 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 100 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 101 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ 102 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 103 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ 104 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 105 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 106 | 107 | /* Completeness */ 108 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 109 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 110 | }, 111 | "include": ["src/**/*"], 112 | "exclude": ["node_modules", "build"] 113 | } 114 | ```