scalar-mock-server
БесплатноБез исполняемых скриптовНе проверенBuild, customize, and troubleshoot OpenAPI mock servers with @scalar/mock-server, including x-handler, x-seed, authentication, and Docker.
от scalar★ 16 482 звезды на GitHubОб этом скилле
Scalar Mock Server Skill
Reference for implementing and debugging mock APIs with @scalar/mock-server.
Use this when you need realistic API responses from an OpenAPI description document, custom request behavior, seeded data, or Docker-based mock environments.
Overview
- Package:
@scalar/mock-server - Runtime: Node.js (package engine:
>=22) - Main API:
createMockServer(options) - Docs:
- Getting started: https://scalar.com/tools/mock-server/getting-started
- Custom request handlers (
x-handler): https://scalar.com/tools/mock-server/custom-request-handler - Data seeding (
x-seed): https://scalar.com/tools/mock-server/data-seeding - Docker: https://scalar.com/tools/mock-server/docker
Quick Start
Fastest way to run a mock server from a local OpenAPI description:
npx @scalar/cli document mock openapi.json --watch
Programmatic setup:
import { serve } from '@hono/node-server'
import { createMockServer } from '@scalar/mock-server'
const app = await createMockServer({
document: './openapi.yaml',
onRequest({ context, operation }) {
console.log(context.req.method, context.req.path, operation.operationId)
},
})
serve({ fetch: app.fetch, port: 3000 })
createMockServer() Options
At least one of the following is required:
document: OpenAPI description document as URL, file path, or objectspecification: deprecated alias fordocument
Optional:
onRequest({ context, operation }): callback before each request is processedonResponse({ context, operation, response }): callback after the mock produced its response; return aResponseto replace it, or nothing to keep it (operationisundefinedfor routes that are not operations)validateRequest: set tofalseto always return a mock response instead of rejecting contract violations with422(default:true)logger: passfalseto silence the authentication instructions printed on startup, or a(line) => voidsink to redirect them (default: logs to the console)
Built-in Behavior
When the server starts, it:
- Processes and loads the OpenAPI description document.
- Seeds schema data from
x-seedextensions (idempotent: only when collection is empty). - Registers authentication routes for declared security schemes.
- Registers operation routes for each path + method.
- Exposes the source document at:
/openapi.json/openapi.yaml
Custom Request Logic with x-handler
Use x-handler in an operation for dynamic behavior instead of static examples.
Helpers available in x-handler:
storefor in-memory persistence (list,get,create,update,delete,clear)fakerfor generated test datareqfor request data (body,params,query,headers)resfor response examples by status code (res['200'],res['404'], ...)
Status behavior:
store.get()/store.update()=>200when found,404when not foundstore.create()=>201store.delete()=>204when deleted,404when not foundstore.list()=>200- Returning
null/undefinedtriggers404(usesresponses.404example/schema when provided)
Seed Data with x-seed
Use x-seed on components.schemas.<SchemaName> to seed initial data at startup.
Helpers available in x-seed:
seed.count(n, factory)seed(array)seed(factory)(single item shortcut)faker,store, andschema
Key rule: the schema key name is used as the collection name.
Docker Usage
Run the Docker image:
docker run -p 3000:3000 scalarapi/mock-server --url https://api.example.com/openapi.yaml
Document source priority (high to low):
--url <URL>OPENAPI_DOCUMENTOPENAPI_DOCUMENT_URL/docsvolume-mounted files
Request validation is on by default (422 for contract violations). Turn it off with --no-validate-request or -e VALIDATE_REQUEST=false; the flag wins over the variable.
Useful routes:
- Mock endpoints: from your OpenAPI paths
- API reference UI:
/scalar - Description document:
/openapi.json,/openapi.yaml
Troubleshooting Checklist
- Confirm the OpenAPI description document is valid and reachable.
- Confirm at least one document source is configured (
document,--url, env var, or mounted file). - If seeded data is missing, check
x-seedexists on schema keys and the collection was empty on startup. - If auth-protected routes return unauthorized responses, verify matching
securitySchemesand request credentials. - If custom logic fails, inspect
x-handlerruntime errors (mock server returns500with handler error details). - For an unhandled
500(one whoseerrorisInternal Server Error), read itsoperationobject — it names the method and OpenAPI path that failed, plus theoperationIdwhen the document declares one.
Установить scalar-mock-server в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл scalar-mock-server?
Build, customize, and troubleshoot OpenAPI mock servers with @scalar/mock-server, including x-handler, x-seed, authentication, and Docker.
Как установить скилл scalar-mock-server?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл scalar-mock-server запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic