Optimal MCP designer
Build the smallest MCP surface that gives an agent complete, safe, and verifiable control of the target system. Finish the implementation and prove the live contract; do not stop at a design, generated files, a successful build, or an endpoint that merely responds.
Keep the three instruction layers separate
Do not blur these audiences:
- Skill-authoring layer: instructions used to create, publish, or install this skill belong to the current authoring task. They do not belong in this skill's downstream MCP implementations.
- MCP-expert layer: this file directs the agent that analyzes a target and builds its MCP server. Architecture choices, source recovery, testing, deployment, and evidence rules belong here.
- Runtime-agent layer: the final MCP server should expose only the concise usage contract an agent needs at runtime: how to discover operations, learn exact schemas, execute safely, authenticate when required, retrieve diagnostics, and open affected records. Do not copy this entire skill, implementation plans, research notes, or internal reasoning into tool descriptions.
Before shipping, inspect every generated instruction and classify it into exactly one layer. Remove leaked build-process text from runtime descriptions.
Completion contract
An MCP is complete only when all applicable items below are true:
- The current codebase, live service contract, data model, authentication model, deployment topology, and operational logs were inspected before implementation.
- The best supported route exists for every required capability, with browser automation reserved for real programmatic gaps and authentication workflows that need it.
- A remote Streamable HTTP endpoint is live at the stable path
/mcp. - The advertised tool surface is compact, while the discoverable operation catalog covers the full authorized domain lifecycle.
- Inputs and structured outputs have exact schemas; pagination, filtering, idempotency, errors, and destructive behavior are explicit.
- Every operation is tenant/account scoped and consequential writes are read back from the owning system.
- Authentication can be established and diagnosed without exposing secrets.
- Persisted, filterable debug events and direct application URLs are available where the product supports them.
- A copy-paste client configuration and environment-variable contract are supplied without secret values.
- Automated contract tests and live remote checks pass at the promised layer.
- The distributable MCP lives in a public, discoverable GitHub repository and a verified public npm package exposes its stdio command through
npxwhen publication credentials are available. - When valid MetaMCP control-plane credentials are available, the published npm command is registered as a public STDIO server inside a public namespace and exposed through an authenticated public MetaMCP endpoint.
If a requirement is genuinely inapplicable, record why with evidence. Do not silently omit it.
1. Recover the target before designing tools
When codebase access exists, treat the repository as the primary implementation surface.
- Resolve the exact repository, branch, worktree, remotes, package manager, runtime, framework, and deployment target. Read local agent instructions and inspect dirty changes before editing.
- Search before building. Locate existing API routes, service functions, schemas, validators, authorization middleware, entity URLs, tests, logs, and deployment configuration.
- Trace representative read and write journeys from UI or API entrypoint to persistence. Reuse those domain services and invariants; make the MCP a thin adapter rather than a second implementation of the product.
- Enumerate the real entities and workflows. For each, record list/search/get/create/update/archive/delete or equivalent actions, relationships, files, history, state transitions, bulk operations, URLs, and diagnostic evidence that agents may need.
- Identify tenant, workspace, organization, and user boundaries. Determine the authenticated principal from server-side credentials; never trust a caller-supplied owner ID by itself.
- Inspect the live contract as well as source. A custom fork, deployed schema, or provider response can differ from documentation and local code.
Create an internal capability ledger with: use case, operation, source of truth, supported route, authorization rule, input schema, output schema, pagination, side effects, idempotency, read-back proof, direct URL, logging, and test evidence. This ledger is MCP-expert working context, not runtime-agent copy.
2. Discover every viable integration route
For each target or external dependency, inspect routes in this order:
- Existing codebase domain/service functions and supported internal application interfaces.
- Current official API, official SDK, CLI, webhooks, event streams, and documented exports.
- Supported GraphQL, database, or provider integration that preserves application invariants.
- Stable unofficial API or reverse-engineered request contract when the official surface cannot cover the required operation.
- Anchor Browser for authentication or capabilities that truly require the provider's interactive web surface.
Use Context7 throughout integration work: resolve the exact current library or product, retrieve focused official documentation before choosing a contract, and query again for new errors or ambiguous behavior. Match the deployed or installed version. If Context7 lacks coverage, use current official documentation and current source or live schemas.
Always check whether useful unofficial APIs exist, even when an official API exists. Record what extra capability they offer, their authentication and rate limits, stability, maintenance, terms, data fidelity, and failure behavior. Prefer the official or code-native route whenever it performs and verifies the operation adequately. Do not replace a reliable supported route with a brittle browser or unofficial call merely because it exists.
One failed route does not justify disabling a capability. Before adding a temporary gate, test at least three meaningfully distinct approaches across at least two evidence layers, unless the provider contract proves the capability impossible. Keep any unavoidable gate narrow, reversible, observable, and documented with the exact failing condition and removal trigger.
Classify the MCP before choosing its architecture
Classify each capability as codebase-native, API-key API, OAuth API, persistent browser identity, hybrid API/browser, self-hosted multi-route, event/action, data/analytics, or CLI/infrastructure/device control. When a target spans types, classify each capability separately. One browser-only action must not turn the entire MCP into a browser wrapper, and one API endpoint must not hide missing interactive state.
3. Design a compact surface without losing capability
Choose the public tool shape from measured schema size and domain complexity:
For a genuinely small, stable surface, expose direct well-named tools.
For a broad product, large schemas, or more than roughly ten operations, default to three public meta-tools backed by a typed internal operation registry:
get_tool_catalog: browse small summaries by category, search term, or cursor. Its description begins withSTEP 1and says not to guess operation names.learn_tools: return descriptions, input schemas, output schemas, mutability, authorization requirements, and examples for several exact operation names in one call.execute_tool: execute one learned operation with arguments validated against the same registered schema.
The three-tool pattern reduces initial context cost; it must not weaken validation or hide capability. Keep a single registry as the source for catalog entries, learned schemas, execution dispatch, annotations, and tests. Unknown operations and unknown arguments fail explicitly.
Use product-appropriate categories, normally including:
SYSTEM: health, version, feature/configuration status, limits.AUTH: account scope, connection status, identity bootstrap, session status.SEARCH: global search, entity resolution, deduplication candidates.- Domain categories: complete lifecycle and relationships for every core entity.
CONTEXTorFILES: reusable context, attachments, original files, provenance, and history when applicable.DEBUG: persisted events, correlation lookup, operational status.NAVIGATION: direct current-domain URLs for exact entities and workflows.ADMIN: only authorized bounded administration, never an unrestricted escape hatch.
Do not create a generic arbitrary HTTP, SQL, shell, browser-script, or internal-function execution tool. Complete control means complete modeled operations, not unbounded execution.
4. Specify every operation precisely
Each operation definition must include:
- A unique stable name and a short task-oriented description.
- Strict JSON Schema input with required fields, limits, enums, formats, and
additionalProperties: falsewhere appropriate. - An output schema and structured result. Also return a concise text representation when clients need compatibility.
- Read-only, idempotent, destructive, open-world, and other applicable annotations.
- Principal and tenant scope derived server-side.
- Cursor pagination for potentially unbounded collections, stable ordering,
hasNextPage, and an opaquenextCursor. - Filters that reflect real indexed/provider fields; do not pretend unsupported filters work.
- An idempotency key or natural uniqueness rule for retryable creates and consequential actions.
- Concurrency protection for updates when stale writes matter.
- A normalized error with
code,message,retryable,correlationId, and safe details. - A direct application URL when a human can inspect the exact result.
- The exact persisted read-back needed before success is returned.
Keep protocol errors distinct from tool execution errors. Invalid MCP envelopes and unknown public tools use JSON-RPC errors; domain validation or provider failures return a tool result with isError: true and a structured safe error.
For mutable domains, cover the entire useful lifecycle and obvious siblings. Distinguish archive, soft delete, hard delete, cancel, and state transition. Expose hard deletion only when the product supports it and authorization is explicit. Never claim all or complete from one example operation.
5. Put only essential guidance in the runtime MCP
The final MCP server instructions and public descriptions should tell runtime agents:
- Call
get_tool_catalogfirst. - Batch every needed operation into one
learn_toolscall. - Call
execute_toolonly with an exact learned name and matching arguments. - Read back writes and use returned direct URLs for human-visible verification.
- Use AUTH operations when credentials or an interactive provider session are required.
- Use DEBUG operations with correlation IDs and pagination when execution fails.
If direct tools are used instead, omit the artificial three-step sequence and keep each description self-sufficient. Runtime guidance must remain short, action-oriented, and free of design history, private research, prompts, TODOs, or unsupported claims.
6. Implement Anchor Browser identity-backed authentication
When a target has browser-only capabilities or an interactive login, implement Anchor Browser calls inside the final MCP server's AUTH subsystem. Do not make the runtime agent reproduce raw curl commands.
Use these server-side environment names unless the target already has a well-established equivalent:
ANCHOR_BROWSER_API_KEY: Anchor API credential. Required whenever Anchor operations are enabled.ANCHOR_BROWSER_IDENTITY_ID: stable identity pointer for the target account. It may seed a tenant-specific stored mapping.ANCHOR_BROWSER_PROFILE_ID: optional persisted browser profile when the current Anchor contract uses a profile to retain cookies, local storage, cache, and a dedicated sticky IP.- Target credential names such as
TARGET_USERNAME,TARGET_PASSWORD, orTARGET_TOTP_SECRETonly when identity creation needs them. Define names in.env.example; never include values in source, schemas, logs, tool results, or client configuration.
Keep ANCHOR_BROWSER_API_KEY server-side and send it only as the anchor-api-key header to https://api.anchorbrowser.io. If an official SDK expects a different environment name, map this canonical server setting explicitly rather than silently changing the public configuration contract.
Implement a modeled operation such as ensure_browser_auth with this idempotent flow:
- Resolve the identity for the authenticated MCP tenant and target origin. Prefer the tenant-specific stored identity ID, then
ANCHOR_BROWSER_IDENTITY_IDas the configured seed. - If an identity ID exists, call
GET /v1/identities/{identityId}. - On
200, verify that its source belongs to the allowlisted target origin. Record itspending,validated, orfailedstatus without returning credentials or metadata that may contain secrets. - On a genuine
404, acquire an idempotency lock and callPOST /v1/identitiesonce with the allowlisted login/source URL, a non-sensitive name, and server-side credentials when configured. Persist the returned identity ID in the target's existing durable secret/configuration store or tenant mapping. Never create a new identity for timeouts,401,403,429, or5xxresponses. - Start a session with
POST /v1/sessionsusing the resolved identity:
{
"session": { "proxy": { "active": true } },
"browser": {
"captcha_solver": { "active": true },
"extra_stealth": { "active": true }
},
"identities": [{ "id": "resolved-identity-id" }],
"identity_skip_validation": false
}
- Validate the actual response schema. Capture the session ID and interactive
live_view_url; do not log connection credentials or raw profile data. - Verify provider authentication at an allowlisted account/status URL or with a stable account marker.
identity_skip_validation: falsecan refresh stale authentication, but session creation alone is not proof that provider login succeeded. - If MFA, consent, or another human intervention remains, return a structured
actionRequiredstate with the session ID, safe reason, expiry, andliveViewUrl. Preserve the same session for continuation. Never report authenticated until the provider-visible check passes.
For providers whose risk controls depend on network and browser continuity, reuse the same identity/profile and configure a dedicated sticky IP or a proven fixed custom proxy. A country-selected or merely active proxy does not prove a stable IP. Current Anchor profiles can preserve cookies, local storage, and cache; use the current supported identity/profile contract and verify the outbound IP in two separate sessions before claiming continuity. Keep proxy credentials server-side.
Return a result shaped like:
{
"identityId": "uuid",
"identityStatus": "validated",
"sessionId": "uuid",
"sessionStatus": "ready",
"authenticationStatus": "authenticated",
"actionRequired": null,
"liveViewUrl": "https://...",
"targetUrl": "https://target.example/account",
"expiresAt": "2026-01-01T00:00:00Z",
"correlationId": "uuid"
}
Use enums that also cover not_configured, identity_missing, authenticating, human_intervention_required, unauthenticated, and failed. Return identity IDs and session URLs only to the authorized tenant. Validate target URLs against an allowlist to prevent SSRF or cross-account navigation.
Add focused AUTH operations when needed to retrieve session/auth status, continue the same session after human intervention, and close a session. Do not expose a general-purpose browser control primitive unless browser control itself is the product's explicitly authorized domain.
7. Support stdio and remote Streamable HTTP from one core
Keep domain operations and validation transport-independent. Bind the same registry to:
- a stdio executable distributed through npm and runnable with
npx; and - remote Streamable HTTP at
/mcp, either directly in the product or through a verified gateway such as MetaMCP.
Do not fork tool schemas, authorization, error behavior, or business logic by transport. Run the same contract suite against both entrypoints.
Stdio requirements
- The executable starts with
#!/usr/bin/env node, is included in the npm tarball, and is mapped throughpackage.json#bin. - Write only MCP protocol messages to stdout. Send diagnostic output to stderr or persisted logs.
- Handle
SIGINT,SIGTERM, client disconnect, and child-resource cleanup without corrupting protocol output. - Read target credentials from explicitly allowlisted environment names. Never bake credentials into the npm package or copied client configuration.
- A clean-directory client can initialize the exact published package with
npx -y <package>@<version>and call a real harmless tool.
Supply a copy-paste stdio client fragment using the final package and command:
{
"mcpServers": {
"product-name": {
"command": "npx",
"args": ["-y", "@owner/product-mcp@latest"]
}
}
}
Remote Streamable HTTP requirements
Use the official MCP SDK that matches the existing codebase unless current source proves it unsuitable. Implement the current negotiated protocol rather than hand-rolling JSON-RPC.
- Mount the MCP transport at exactly
/mcpon the application's origin. Keep the path independent of deployment domain. - Support the normative initialize handshake, protocol-version negotiation, client/server capabilities, and
notifications/initializedlifecycle. - For Streamable HTTP POST, require
Content-Type: application/json. Require clients'Acceptheader to include bothapplication/jsonandtext/event-stream, then return a JSON response or an SSE stream according to the negotiated protocol behavior. Support GET SSE or explicitly return405when server-to-client streaming is not offered. - If the server issues
Mcp-Session-Id, make it cryptographically secure and require it on subsequent session requests. A stateless SDK configuration is acceptable only when all operations and authentication remain correct without an MCP session. - Validate
Origin, apply robust MCP authentication and authorization, and rate-limit abusive traffic. Local servers bind to localhost; remote servers use TLS. - Keep
/healthor an equivalent service check separate from MCP success. An HTTP200at health does not prove initialize or tool execution. - Generate direct application URLs from a validated public base URL or the current request origin. Never hardcode a previous deployment domain.
Supply a copy-paste client fragment using the actual deployed origin:
{
"mcpServers": {
"product-name": {
"type": "http",
"url": "https://product.example/mcp"
}
}
}
Keep secret values out of copied settings. Use the client's supported header, OAuth, or secret-storage mechanism for MCP authentication.
8. Create the public MCP distribution repository
The authoritative standalone MCP distribution repo belongs at:
/Users/samihalawa/git/PROJECTS_MCP_TOOLS/<mcp-repo-name>
Use a clear -mcp suffix. If that path does not exist in the current environment, use the user's established MCP-tools root or the current workspace without inventing an unrelated directory.
For codebase-native MCPs, keep business logic and invariants in the product. The public MCP repo should contain only the safe transport/client adapter and public contracts needed to reach those supported services. Do not copy proprietary application code, private schemas, customer data, or secrets merely to make the adapter standalone. The direct product /mcp route and public package must share or verify one operation contract rather than evolving independently.
The MCP repo is public by default. Before publication, include the normal public package artifacts needed by this MCP—not by this skill—including:
README.mdwith a literal product description, capabilities, tool-discovery flow, install commands, client configurations, environment-variable names, examples, limitations, and verification steps;LICENSE, preserving the upstream license when applicable and otherwise using the user's chosen permissive license;package.json, lockfile, source, tests, build configuration, and the smallest required runtime files;.gitignore,.npmignoreorpackage.json#files, and an.npmrccontaining only an environment placeholder if used;- accurate package keywords such as
mcp,mcp-server,model-context-protocol,ai-agents, and target-specific terms.
Optimize discoverability without fabricated popularity signals. Use a precise repository name and description, useful README headings, working examples, accurate GitHub topics, npm keywords, and the live endpoint as homepage when appropriate. Never invent stars, downloads, adoption, compatibility, or security claims.
Before evaluating any publication gate, load the private environment owned by the installed skill as well as the global environment. The installed-skill file takes precedence so its configured publishing credentials are actually available to GitHub, npm, and MetaMCP commands:
skill_env_path="${HOME}/.agents/skills/optimal-mcp-designer-skill/.env"
set -a
[ -r "${HOME}/.env" ] && . "${HOME}/.env"
[ -r "$skill_env_path" ] && . "$skill_env_path"
set +a
Keep that adjacent .env installation-local with mode 600. Never copy it into a target MCP repo, add it to git, include it in an npm tarball, print its values, or place its values in generated documentation. Use these loaded names:
GH_TOKEN, falling back toGITHUB_TOKENfor GitHub CLI and API access;MCP_REPO_OWNER, otherwise resolve the authenticated GitHub login;MCP_REPO_NAME, otherwise derive a unique target-specific-mcpname;NPMJS_TOKEN,NPM_PACKAGE_NAME, andMCP_COMMAND_NAMEfor npm distribution;METAMCP_API_KEYandMETAMCP_BASE_URL, defaulting the base URL tohttps://metamcp.megawebs.comin this environment;- target MCP runtime variables such as provider API keys or Anchor settings, added only when required by the actual integration.
Never publish or persist the credential values supplied to the build agent. Scan the git index and npm tarball for secrets, local paths, private hostnames, .env files, cookies, tokens, fixtures with real user data, and internal-only instructions before publication.
Initialize and publish after tests and public-artifact review pass:
mcp_repo_root="/Users/samihalawa/git/PROJECTS_MCP_TOOLS"
mcp_repo_name="${MCP_REPO_NAME:-product-mcp}"
mcp_repo_dir="${mcp_repo_root}/${mcp_repo_name}"
cd "$mcp_repo_dir"
git status --short --branch
git init -b main # only for a genuinely new standalone repo
git add <reviewed-public-files>
git commit -m "Create and publish the complete <product> MCP"
export GH_TOKEN="${GH_TOKEN:-${GITHUB_TOKEN:-}}"
repo_owner="${MCP_REPO_OWNER:-$(gh api user --jq .login)}"
gh repo create "${repo_owner}/${mcp_repo_name}" --public --source=. --remote=origin --push
gh repo edit "${repo_owner}/${mcp_repo_name}" \
--description "<precise target-specific MCP description>" \
--homepage "<live MCP or documentation URL>"
gh api --method PUT "repos/${repo_owner}/${mcp_repo_name}/topics" \
-f 'names[]=mcp' \
-f 'names[]=mcp-server' \
-f 'names[]=model-context-protocol' \
-f 'names[]=ai-agents'
For an existing repo, fetch, inspect, fast-forward the actual default branch, commit only in-scope files, and push instead of reinitializing or creating a duplicate. Verify public visibility, default-branch SHA, raw-file hashes, description, homepage, and topics after publication.
If neither GH_TOKEN nor GITHUB_TOKEN is set or valid, still complete and validate the MCP in the required local folder. Report LOCAL_READY_GITHUB_NOT_PUBLISHED with the exact missing variable or rejected authorization; continue any later stage that does not depend on GitHub.
9. Publish the stdio MCP to npm
Make the package independently runnable. A typical manifest includes:
{
"name": "@owner/product-mcp",
"version": "0.1.0",
"type": "module",
"bin": {
"product-mcp": "dist/stdio.js"
},
"files": ["dist", "README.md", "LICENSE"],
"publishConfig": {
"access": "public"
}
}
Use the repo's language and build system rather than forcing this exact layout. Ensure the built bin target exists, retains its Node shebang and executable mode, and includes all runtime dependencies. Keep development-only files, source maps containing private paths, tests with private fixtures, .env files, and secrets out of the tarball.
Before selecting a name, query npm. If an unscoped name is occupied, prefer a truthful public scoped name rather than imitating another package. Use semantic versioning and never overwrite an already published version.
Validate and publish:
npm_package_name="${NPM_PACKAGE_NAME:-@owner/product-mcp}"
npm_package_version="$(node -p 'require("./package.json").version')"
npm ci
npm test
npm run build
npm pack --dry-run --json
if [ -z "${NPMJS_TOKEN:-}" ]; then
echo "PACKAGE_READY_NPM_NOT_PUBLISHED: NPMJS_TOKEN is missing"
else
npmrc_file="$(mktemp)"
chmod 600 "$npmrc_file"
trap 'rm -f "$npmrc_file"' EXIT
printf '%s\n' '//registry.npmjs.org/:_authToken=${NPMJS_TOKEN}' > "$npmrc_file"
NPM_CONFIG_USERCONFIG="$npmrc_file" npm publish --access public
fi
npm view "${npm_package_name}@${npm_package_version}" \
name version dist.tarball dist.integrity bin --json
Do not run npm publish when NPMJS_TOKEN is absent, invalid, or when that exact version already exists. In those cases, preserve the built and pack-verified repo and report the precise publication state without blocking GitHub or direct HTTP deployment.
After registry read-back, create a clean temporary directory and connect a real MCP stdio client to:
npx -y "${npm_package_name}@${npm_package_version}"
Prove initialize, initialized notification, tools/list, and one harmless tools/call against the registry-installed package. Running from the source checkout does not prove the npm package is complete.
Commit and push any version or generated lockfile change that is part of the published package, create a matching Git tag and GitHub release when appropriate, and verify the release points to the npm version's source commit.
10. Publish the npm command through MetaMCP when configured
MetaMCP calls a namespace a grouping of MCP servers; treat it as the requested public MCP space. Perform this stage only when all of the following are true:
METAMCP_API_KEYis set and accepted by the current MetaMCP control-plane contract;METAMCP_BASE_URLis reachable;- the exact npm package version has been read back from npm; and
- the published package passes the clean-directory stdio canary.
Missing or invalid MetaMCP configuration skips only this stage. Report NPM_PUBLISHED_METAMCP_NOT_PUBLISHED and the exact failed prerequisite; do not undo or hide the successful local, GitHub, or npm layers.
Inspect the deployed MetaMCP source or current API schema before mutation. The current resource families are MCP servers, namespaces, namespace server/tool mappings, endpoints, API keys, and OAuth. Current typed control-plane procedures may be named frontend.mcpServers.*, frontend.namespaces.*, and frontend.endpoints.*, but their transport and authorization can differ by deployment. Use the supported management REST, typed tRPC client, authenticated native session, or authorized deployment database route that can create and read back the exact resources. Do not assume an endpoint API key also authenticates the management API.
Reconcile by exact name before creating anything. Update matching resources instead of duplicating them. Use current schemas to create or converge these public resources:
- A public MCP server:
{
"name": "product-mcp",
"description": "Public stdio MCP for <product>",
"type": "STDIO",
"command": "npx",
"args": ["-y", "@owner/product-mcp@0.1.0"],
"env": {},
"user_id": null
}
Include only the target runtime environment variables actually required by the stdio process. Never pass GH_TOKEN, GITHUB_TOKEN, NPMJS_TOKEN, or METAMCP_API_KEY into the child MCP environment.
- A public namespace containing that exact server UUID:
{
"name": "product-mcp",
"description": "Public namespace for <product> MCP tools",
"mcpServerUuids": ["server-uuid"],
"user_id": null
}
- A public endpoint bound to that namespace:
{
"name": "product-mcp",
"description": "Authenticated public endpoint for <product> MCP",
"namespaceUuid": "namespace-uuid",
"enableApiKeyAuth": true,
"useQueryParamAuth": true,
"enableOauth": true,
"enableMetamcpAdminTools": false,
"enableMaxRate": false,
"enableClientMaxRate": false,
"createMcpServer": false,
"user_id": null
}
Public ownership is represented by the current deployment's public/null owner contract; verify rather than assuming that exact field remains unchanged. Keep MetaMCP admin tools disabled unless the user explicitly requests exposing administration and the endpoint has a separate least-privilege authorization design.
Refresh tool discovery, enable the server inside the namespace, and enable every intended tool mapping. Read back the server type, command, exact versioned args, public ownership, namespace membership, server status, tool names/statuses, endpoint namespace, and all three requested authentication flags.
The resulting public URLs normally follow:
${METAMCP_BASE_URL}/metamcp/<endpoint-name>/mcp
${METAMCP_BASE_URL}/metamcp/<endpoint-name>/sse
${METAMCP_BASE_URL}/metamcp/<endpoint-name>/api
${METAMCP_BASE_URL}/metamcp/<endpoint-name>/api/openapi.json
Test the exact /mcp endpoint with a clean MCP client using an authorized header. Separately test query authentication using --get --data-urlencode "api_key=$METAMCP_API_KEY" without printing or retaining the expanded URL. Verify OAuth discovery and a real bearer-token flow when the deployed OAuth beta supports it. API-key success does not prove OAuth, and an OpenAPI document does not prove MCP initialize or tool execution.
Return the clean endpoint URL without its API key. Never put query-string credentials in GitHub, npm metadata, README examples, logs, screenshots, or final reports.
11. Apply the distribution gates independently
Always finish the local implementation and validation. Then advance each available layer without making a missing later credential erase earlier progress:
- No GitHub credential: validated local public-ready repo remains in
PROJECTS_MCP_TOOLS. - Valid GitHub credential: public repo, optimized metadata, pushed commit, and remote equality proof.
- Valid
NPMJS_TOKEN: public npm package, registry read-back, and cleannpxstdio proof. - Valid
METAMCP_API_KEYplus published npm package: public STDIO server, public namespace, all intended tools enabled, authenticated public endpoint, and live/mcpproof.
Report every layer as COMPLETE, SKIPPED_MISSING_ENV, BLOCKED_INVALID_AUTH, or FAILED_CONTRACT, with exact evidence. Never describe a skipped layer as deployed.
12. Make authentication and isolation native
Authenticate the MCP itself independently from any target browser session. Prefer existing application access tokens or OAuth when they bind naturally to users and tenants. Map the token to the owning principal server-side, enforce authorization again inside every operation, and never accept tenant scope solely from tool arguments.
Cover:
- Token creation, revocation, expiration, rotation, and last-used evidence when the product owns token management.
- Constant-time secret comparison or the framework's proven verifier.
- Least-privilege scopes for read, write, destructive, diagnostic, and browser-auth operations.
- Tenant-scoped caches, logs, idempotency keys, files, identity mappings, and direct URLs.
- Redaction of authorization headers, cookies, passwords, API keys, authenticator secrets, sensitive request bodies, and session connection URLs from logs, persistence, diagnostics, and unauthorized responses. An authorized tenant may receive its own short-lived
liveViewUrldirectly from an AUTH operation when human continuation is required; do not persist or log that URL.
Test with at least two principals to prove that cross-tenant reads, writes, logs, browser identities, and URLs are rejected.
13. Expose useful diagnostics, not secret dumps
Persist bounded structured events for MCP and underlying provider operations. Include timestamp, level, source, event, operation, principal/tenant reference, entity reference when safe, duration, outcome, provider request ID, and correlation ID. Redact before persistence.
Provide a get_debug_logs-style operation with newest-first stable ordering, time range, level, source, event, operation, entity, and correlation filters plus cursor pagination. Return full safe structured details needed to diagnose the incident. A status summary is not a substitute for the relevant log window.
Correlate catalog/learn/execute failures, validation failures, provider calls, write/read-back mismatches, Anchor identity/session events, and deployment/runtime errors. Logs prove recorded backend events, not the user-visible result; verify the application or provider surface separately when promised.
14. Return navigation and provenance
For every primary entity or workflow with a UI, add a typed navigation operation or url field that opens the exact entity on the current application domain. Build URLs from canonical IDs, validate ownership before returning them, and test that the route renders the expected entity.
Results should also identify the source of truth, entity ID, version or update timestamp, and correlation ID. For files and context, preserve filename, media type, size, checksum when available, origin, relationships, and current download/view URL without leaking storage credentials.
15. Implement in the existing architecture
Use existing validators, service functions, authorization middleware, URL builders, logging, test fixtures, and deployment route conventions. Add one registry and one adapter layer rather than wrappers around wrappers. Do not introduce a second database model, migration, service, queue, or API solely for MCP when existing product primitives can represent the requirement.
When no codebase exists, choose a maintained official SDK and the lightest production runtime that satisfies transport, authentication, schemas, observability, and deployment needs. Generate only the files needed to build, run, test, and deploy the server.
After each failure, inspect the exact error and current contract. For external libraries or APIs, make a focused Context7 lookup before changing the approach. Do not retry unchanged requests blindly.
16. Validate every proof layer
Run proportionate automated and live tests. At minimum, cover:
- Static validation, type checking, linting, unit tests, production build, and dependency audit appropriate to the repository.
- A real SDK client initialize handshake against
/mcp, followed by initialized notification,tools/list, andtools/call. - The exact public tool count and names.
- Catalog filtering/pagination, one batched learn call, learned input/output schemas, and execution using the learned schema.
- Unknown public tool, unknown internal operation, invalid argument, provider failure, timeout, and safe error behavior.
- At least one representative read and authorized write/read-back round trip for every domain category.
- Complete pagination over a multi-page fixture and a live bounded collection.
- Idempotent create/retry and concurrency behavior.
- Destructive-operation authorization and explicit semantics.
- Persisted debug retrieval by correlation ID.
- Direct URL generation and a rendered or provider-native check of the exact entity.
- MCP authentication, revocation, rate limits, Origin validation, and two-principal tenant isolation.
- Anchor identity found, identity
404then single creation, non-404 failures without creation, stale identity validation, authenticated session, human-intervention continuation, target-origin allowlist, and secret redaction. - The deployed remote URL from a clean client using the copy-paste configuration.
- The exact npm tarball allowlist, registry version/integrity/bin read-back, and clean-directory
npxstdio handshake. - Public GitHub visibility, metadata/topics, default-branch SHA, tag/release when used, and raw-file equality.
- When configured, MetaMCP public ownership, STDIO command and exact package version, namespace membership, enabled tool mappings, endpoint flags, header/query API-key paths, OAuth flow, and live remote tool call.
Mock tests prove deterministic branches; they do not prove external authentication, deployment, persistence, or rendered UI. Use a bounded non-destructive live canary for those layers and record the exact IDs, timestamps, responses, and read-backs.
17. Deliver a reproducible handoff
Return:
- What MCP capability was implemented and what existing architecture it reuses.
- The exact remote
/mcpURL and a copy-paste client configuration. - The public GitHub repo, npm package/version,
npxcommand, and stdio client configuration. - The MetaMCP server, namespace, endpoint, clean public URLs, and authentication modes when that stage ran.
- Environment-variable names and which are required, with no values.
- Public tool names and count; internal operation categories and count.
- Authentication and tenant-isolation behavior.
- Anchor identity/session behavior and how human intervention resumes.
- Debug-log and direct-URL capabilities.
- Tests/build/deployment results and live proof at each layer.
- Exact files and repository revision.
- A layer-by-layer local/GitHub/npm/MetaMCP status using the defined completion states.
- Any genuinely unresolved capability, its evidence, and the narrow next action.
Use precise states: implemented, tested, deployed, connected, authenticated, persisted, rendered, and provider-confirmed are different. Claim completion only when the requested final state has been read back at its owning layer.