// src/application/context-storage/index.ts
import {
  EmbeddingService,
  VectorIndexer
} from "@contractspec/lib.knowledge/ingestion";
import {
  ContextSnapshotPipeline,
  PostgresContextStorage
} from "@contractspec/module.context-storage";
function createContextStorageService(options) {
  const store = new PostgresContextStorage({
    database: options.database,
    schema: options.schema,
    createTablesIfMissing: options.createTablesIfMissing
  });
  const embeddingService = options.embeddingProvider ? new EmbeddingService(options.embeddingProvider, options.embeddingBatchSize) : undefined;
  const vectorIndexer = options.vectorStoreProvider && options.vectorIndex ? new VectorIndexer(options.vectorStoreProvider, options.vectorIndex) : undefined;
  const pipeline = new ContextSnapshotPipeline({
    store,
    documentProcessor: options.documentProcessor,
    embeddingService,
    vectorIndexer
  });
  return { store, pipeline };
}

// src/application/mcp/common.ts
import { PresentationRegistry } from "@contractspec/lib.contracts-spec/presentations";
import { createMcpServer } from "@contractspec/lib.contracts-runtime-server-mcp/provider-mcp";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
import { Elysia } from "elysia";
import { randomUUID } from "node:crypto";
var baseCtx = {
  actor: "anonymous",
  decide: async () => ({ effect: "allow" })
};
function createJsonRpcErrorResponse(status, code, message, data) {
  return new Response(JSON.stringify({
    jsonrpc: "2.0",
    error: {
      code,
      message,
      ...data ? { data } : {}
    },
    id: null
  }), {
    status,
    headers: {
      "content-type": "application/json"
    }
  });
}
function createSessionState({
  logger,
  serverName,
  ops,
  resources,
  prompts,
  presentations,
  stateful
}) {
  const server = new McpServer({
    name: serverName,
    version: "1.0.0"
  }, {
    capabilities: {
      tools: {},
      resources: {},
      prompts: {},
      logging: {}
    }
  });
  logger.info("Setting up MCP server...");
  createMcpServer(server, ops, resources, prompts, {
    logger,
    toolCtx: () => baseCtx,
    promptCtx: () => ({ locale: "en" }),
    resourceCtx: () => ({ locale: "en" }),
    presentations: new PresentationRegistry(presentations)
  });
  const transport = new WebStandardStreamableHTTPServerTransport({
    sessionIdGenerator: stateful ? () => randomUUID() : undefined,
    enableJsonResponse: true
  });
  return server.connect(transport).then(() => ({ server, transport }));
}
async function closeSessionState(state) {
  await Promise.allSettled([state.transport.close(), state.server.close()]);
}
function toErrorMessage(error) {
  return error instanceof Error ? error.stack ?? error.message : String(error);
}
function createMcpElysiaHandler({
  logger,
  path,
  serverName,
  ops,
  resources,
  prompts,
  presentations,
  validateAuth,
  requiredAuthMethods
}) {
  logger.info("Setting up MCP handler...", {
    requiredAuthMethods: requiredAuthMethods ?? []
  });
  const isStateful = process.env.CONTRACTSPEC_MCP_STATEFUL === "1";
  const sessions = new Map;
  async function handleStateless(request) {
    const state = await createSessionState({
      logger,
      path,
      serverName,
      ops,
      resources,
      prompts,
      presentations,
      stateful: false
    });
    try {
      return await state.transport.handleRequest(request);
    } finally {
      await closeSessionState(state);
    }
  }
  async function closeSession(sessionId) {
    const state = sessions.get(sessionId);
    if (!state)
      return;
    sessions.delete(sessionId);
    await closeSessionState(state);
  }
  async function handleStateful(request) {
    const requestedSessionId = request.headers.get("mcp-session-id");
    let state;
    let createdState = false;
    if (requestedSessionId) {
      const existing = sessions.get(requestedSessionId);
      if (!existing) {
        return createJsonRpcErrorResponse(404, -32001, "Session not found");
      }
      state = existing;
    } else {
      state = await createSessionState({
        logger,
        path,
        serverName,
        ops,
        resources,
        prompts,
        presentations,
        stateful: true
      });
      createdState = true;
    }
    try {
      const response = await state.transport.handleRequest(request);
      const activeSessionId = state.transport.sessionId;
      if (activeSessionId && !sessions.has(activeSessionId)) {
        sessions.set(activeSessionId, state);
      }
      if (request.method === "DELETE" && activeSessionId) {
        await closeSession(activeSessionId);
      } else if (!activeSessionId && createdState) {
        await closeSessionState(state);
      }
      return response;
    } catch (error) {
      if (createdState) {
        await closeSessionState(state);
      }
      throw error;
    }
  }
  return new Elysia({ name: `mcp-${serverName}` }).all(path, async ({ request }) => {
    try {
      if (validateAuth) {
        const authResult = await validateAuth(request);
        if (!authResult.valid) {
          return createJsonRpcErrorResponse(401, -32002, "Authentication failed", authResult.reason);
        }
      }
      if (isStateful) {
        return await handleStateful(request);
      }
      return await handleStateless(request);
    } catch (error) {
      logger.error("Error handling MCP request", {
        path,
        method: request.method,
        error: toErrorMessage(error)
      });
      return createJsonRpcErrorResponse(500, -32000, "Internal error");
    }
  });
}

// src/infrastructure/elysia/logger.ts
import { Logger, LogLevel } from "@contractspec/lib.logger";
var createAppLogger = () => new Logger({
  level: LogLevel.INFO,
  environment: "production",
  enableTracing: true,
  enableTiming: true,
  enableContext: true,
  enableColors: false
});
var appLogger = createAppLogger();
var dbLogger = new Logger({
  level: LogLevel.WARN,
  environment: "production",
  enableTracing: true,
  enableTiming: true,
  enableContext: true,
  enableColors: false
});
var authLogger = new Logger({
  level: LogLevel.INFO,
  environment: "production",
  enableTracing: true,
  enableTiming: true,
  enableContext: true,
  enableColors: false
});
// src/features/docs/docs.contracts.ts
import {
  DocSummaryModel,
  DocsIndexInput,
  DocsIndexOutput,
  DocsIndexQuery,
  DocsIndexQuery as DocsIndexQuery2,
  ContractReferenceQuery
} from "@contractspec/lib.contracts-spec/docs";
// src/application/mcp/docsMcp.ts
import {
  definePrompt,
  defineResourceTemplate,
  installOp,
  OperationSpecRegistry,
  PromptRegistry,
  ResourceRegistry
} from "@contractspec/lib.contracts-spec";
import { defaultDocRegistry } from "@contractspec/lib.contracts-spec/docs";
import z from "zod";
var DOC_OWNERS = ["@contractspec"];
var DOC_TAGS = ["docs", "mcp"];
function buildDocResources(routes) {
  const resources = new ResourceRegistry;
  resources.register(defineResourceTemplate({
    meta: {
      uriTemplate: "docs://list",
      title: "DocBlocks index",
      description: "All registered DocBlocks with route, visibility, tags, and summary.",
      mimeType: "application/json",
      tags: DOC_TAGS
    },
    input: z.object({}),
    resolve: async () => {
      const docs = routes.map(({ block, route }) => ({
        id: block.id,
        title: block.title,
        summary: block.summary ?? "",
        tags: block.tags ?? [],
        visibility: block.visibility ?? "public",
        route
      }));
      return {
        uri: "docs://list",
        mimeType: "application/json",
        data: JSON.stringify(docs, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate({
    meta: {
      uriTemplate: "docs://doc/{id}",
      title: "DocBlock markdown",
      description: "Fetch DocBlock body by id as markdown.",
      mimeType: "text/markdown",
      tags: DOC_TAGS
    },
    input: z.object({ id: z.string() }),
    resolve: async ({ id }) => {
      const found = defaultDocRegistry.get(id);
      if (!found) {
        return {
          uri: `docs://doc/${encodeURIComponent(id)}`,
          mimeType: "text/plain",
          data: `DocBlock not found: ${id}`
        };
      }
      return {
        uri: `docs://doc/${encodeURIComponent(id)}`,
        mimeType: "text/markdown",
        data: String(found.block.body ?? "")
      };
    }
  }));
  return resources;
}
function buildDocPrompts() {
  const prompts = new PromptRegistry;
  prompts.register(definePrompt({
    meta: {
      key: "docs.navigator",
      version: "1.0.0",
      title: "Find relevant ContractSpec docs",
      description: "Guide agents to pick the right DocBlock by topic or tag.",
      tags: DOC_TAGS,
      stability: "beta",
      owners: DOC_OWNERS
    },
    args: [
      {
        name: "topic",
        description: "Goal or subject to search for.",
        required: false,
        schema: z.string().optional()
      },
      {
        name: "tag",
        description: "Optional tag filter.",
        required: false,
        schema: z.string().optional()
      }
    ],
    input: z.object({
      topic: z.string().optional(),
      tag: z.string().optional()
    }),
    render: async ({ topic, tag }) => {
      const parts = [
        {
          type: "text",
          text: `Use the docs index to choose DocBlocks. If a specific topic is provided, prefer docs whose id/title/summary match it.${topic ? ` Topic: ${topic}.` : ""}${tag ? ` Tag: ${tag}.` : ""}`
        },
        {
          type: "resource",
          uri: "docs://list",
          title: "DocBlocks index"
        }
      ];
      return parts;
    }
  }));
  return prompts;
}
function buildDocOps(routes) {
  const registry = new OperationSpecRegistry;
  installOp(registry, DocsIndexQuery, async (args) => {
    const query = args.query?.toLowerCase().trim();
    const tagsFilter = args.tag?.map((t) => t.toLowerCase().trim()) ?? [];
    const visibility = args.visibility?.toLowerCase().trim();
    const docs = routes.map(({ block, route }) => ({
      id: block.id,
      title: block.title,
      summary: block.summary ?? "",
      tags: block.tags ?? [],
      visibility: (block.visibility ?? "public").toLowerCase(),
      route
    })).filter((doc) => {
      const matchesQuery = query ? doc.id.toLowerCase().includes(query) || doc.title.toLowerCase().includes(query) || doc.summary.toLowerCase().includes(query) : true;
      const matchesTags = tagsFilter.length ? tagsFilter.every((t) => doc.tags.some((tag) => tag.toLowerCase().includes(t))) : true;
      const matchesVisibility = visibility ? doc.visibility === visibility : true;
      return matchesQuery && matchesTags && matchesVisibility;
    });
    return {
      docs,
      items: docs,
      total: docs.length
    };
  });
  return registry;
}
function createDocsMcpHandler(path = "/api/mcp/docs") {
  const routes = defaultDocRegistry.list();
  return createMcpElysiaHandler({
    logger: appLogger,
    path,
    serverName: "contractspec-docs-mcp",
    ops: buildDocOps(routes),
    resources: buildDocResources(routes),
    prompts: buildDocPrompts(),
    presentations: routes.map(({ descriptor }) => descriptor)
  });
}

// src/application/mcp/cliMcp.ts
import fs from "node:fs/promises";
import path from "path";
import {
  defineCommand,
  definePrompt as definePrompt2,
  defineResourceTemplate as defineResourceTemplate2,
  installOp as installOp2,
  OperationSpecRegistry as OperationSpecRegistry2,
  PromptRegistry as PromptRegistry2,
  ResourceRegistry as ResourceRegistry2
} from "@contractspec/lib.contracts-spec";
import { defineSchemaModel, ScalarTypeEnum } from "@contractspec/lib.schema";
import z2 from "zod";
var __dirname = "/home/runner/work/contractspec/contractspec/packages/bundles/library/src/application/mcp";
var CLI_DOC_PATHS = {
  quickstart: "packages/apps/cli-contractspec/QUICK_START.md",
  reference: "packages/apps/cli-contractspec/QUICK_REFERENCE.md",
  readme: "packages/apps/cli-contractspec/README.md"
};
var CLI_DOC_FALLBACK = {
  quickstart: `# ContractSpec CLI quickstart

contractspec create
contractspec build <spec>
contractspec validate <spec>`,
  reference: `# ContractSpec CLI reference

Key commands: create, build, validate. See README for full options.`,
  readme: `# ContractSpec CLI

Stabilize AI-generated code across API, DB, UI, events. Use create/build/validate commands.`
};
var CLI_DOC_TAGS = ["cli", "mcp"];
var CLI_OWNERS = ["@contractspec"];
var candidateRoots = (() => {
  const roots = new Set([
    process.cwd(),
    path.resolve(process.cwd(), ".."),
    path.resolve(process.cwd(), "../.."),
    path.resolve(process.cwd(), "../../..")
  ]);
  if (typeof __dirname === "string") {
    roots.add(path.resolve(__dirname, "../../../../.."));
  }
  return [...roots];
})();
var docCache = new Map;
async function loadCliDoc(key) {
  if (docCache.has(key)) {
    return docCache.get(key);
  }
  const relative = CLI_DOC_PATHS[key];
  for (const root of candidateRoots) {
    const candidate = path.resolve(root, relative);
    try {
      const data = await fs.readFile(candidate, "utf8");
      docCache.set(key, data);
      return data;
    } catch {}
  }
  const fallback = CLI_DOC_FALLBACK[key];
  docCache.set(key, fallback);
  return fallback;
}
function buildCliResources() {
  const resources = new ResourceRegistry2;
  resources.register(defineResourceTemplate2({
    meta: {
      uriTemplate: "cli://doc/{slug}",
      title: "CLI documentation",
      description: "Quickstart, reference, and README for the CLI.",
      mimeType: "text/markdown",
      tags: CLI_DOC_TAGS
    },
    input: z2.object({
      slug: z2.enum(["quickstart", "reference", "readme"])
    }),
    resolve: async ({ slug }) => {
      const data = await loadCliDoc(slug);
      return {
        uri: `cli://doc/${slug}`,
        mimeType: "text/markdown",
        data
      };
    }
  }));
  resources.register(defineResourceTemplate2({
    meta: {
      uriTemplate: "cli://commands",
      title: "CLI commands summary",
      description: "Key ContractSpec CLI commands and when to use them.",
      mimeType: "application/json",
      tags: CLI_DOC_TAGS
    },
    input: z2.object({}),
    resolve: async () => {
      const commands = [
        {
          command: "contractspec create",
          summary: "Interactive wizard to author specs (with optional AI).",
          doc: "cli://doc/quickstart"
        },
        {
          command: "contractspec build <specPath>",
          summary: "Generate implementation code from a ContractSpec (agents + templates).",
          doc: "cli://doc/reference"
        },
        {
          command: "contractspec validate <specPath>",
          summary: "Validate specs and optionally check implementations against them.",
          doc: "cli://doc/reference"
        }
      ];
      return {
        uri: "cli://commands",
        mimeType: "application/json",
        data: JSON.stringify(commands, null, 2)
      };
    }
  }));
  return resources;
}
function buildCliPrompts() {
  const prompts = new PromptRegistry2;
  prompts.register(definePrompt2({
    meta: {
      key: "cli.usage",
      version: "1.0.0",
      title: "Use ContractSpec CLI safely",
      description: "Remind agents to read CLI docs and pick commands from the canonical list.",
      tags: CLI_DOC_TAGS,
      stability: "beta",
      owners: CLI_OWNERS
    },
    args: [
      {
        name: "goal",
        description: "Task the user wants to achieve.",
        required: false,
        schema: z2.string().optional()
      }
    ],
    input: z2.object({ goal: z2.string().optional() }),
    render: async ({ goal }) => [
      {
        type: "text",
        text: `Use CLI commands only from cli://commands. Prefer quickstart for newcomers and reference for options.${goal ? ` Goal: ${goal}.` : ""}`
      },
      { type: "resource", uri: "cli://commands", title: "Commands" },
      {
        type: "resource",
        uri: "cli://doc/quickstart",
        title: "Quickstart"
      }
    ]
  }));
  return prompts;
}
function buildCliOps() {
  const registry = new OperationSpecRegistry2;
  const CliSuggestInput = defineSchemaModel({
    name: "CliSuggestInput",
    fields: {
      goal: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
      prefersAi: { type: ScalarTypeEnum.Boolean(), isOptional: true }
    }
  });
  const CliSuggestOutput = defineSchemaModel({
    name: "CliSuggestOutput",
    fields: {
      command: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
      docUri: { type: ScalarTypeEnum.String_unsecure(), isOptional: false },
      reason: { type: ScalarTypeEnum.String_unsecure(), isOptional: false }
    }
  });
  const suggestSpec = defineCommand({
    meta: {
      key: "cli.suggestCommand",
      version: "1.0.0",
      stability: "stable",
      owners: CLI_OWNERS,
      tags: CLI_DOC_TAGS,
      description: "Recommend a CLI command for the requested goal.",
      goal: "Help AI agents choose the correct CLI entrypoint quickly.",
      context: "Used inside the CLI MCP server."
    },
    io: {
      input: CliSuggestInput,
      output: CliSuggestOutput
    },
    policy: {
      auth: "anonymous"
    }
  });
  installOp2(registry, suggestSpec, async ({ goal, prefersAi }) => {
    const lower = goal.toLowerCase();
    if (lower.includes("create") || lower.includes("new")) {
      return {
        command: prefersAi ? "contractspec create --ai" : "contractspec create",
        docUri: "cli://doc/quickstart",
        reason: "Creates a new ContractSpec interactively (optionally with AI)."
      };
    }
    if (lower.includes("build") || lower.includes("generate")) {
      return {
        command: "contractspec build <path-to-spec>",
        docUri: "cli://doc/reference",
        reason: "Builds implementation code from a spec using agents + templates."
      };
    }
    if (lower.includes("validate") || lower.includes("check")) {
      return {
        command: "contractspec validate <path-to-spec>",
        docUri: "cli://doc/reference",
        reason: "Validates a spec and optionally checks its implementation for drift."
      };
    }
    return {
      command: "contractspec --help",
      docUri: "cli://doc/readme",
      reason: "Fallback when the goal is unclear; read README for options."
    };
  });
  return registry;
}
function createCliMcpHandler(path2 = "/api/mcp/cli") {
  return createMcpElysiaHandler({
    logger: appLogger,
    path: path2,
    serverName: "contractspec-cli-mcp",
    ops: buildCliOps(),
    resources: buildCliResources(),
    prompts: buildCliPrompts()
  });
}

// src/application/mcp/internalMcp.ts
import {
  defineCommand as defineCommand2,
  definePrompt as definePrompt3,
  defineResourceTemplate as defineResourceTemplate3,
  installOp as installOp3,
  OperationSpecRegistry as OperationSpecRegistry3,
  PromptRegistry as PromptRegistry3,
  ResourceRegistry as ResourceRegistry3
} from "@contractspec/lib.contracts-spec";
import { defineSchemaModel as defineSchemaModel2, ScalarTypeEnum as ScalarTypeEnum2 } from "@contractspec/lib.schema";
import z3 from "zod";
import {
  getExample,
  listExamples,
  searchExamples
} from "@contractspec/module.examples";
var INTERNAL_TAGS = ["internal", "mcp"];
var INTERNAL_OWNERS = ["@contractspec"];
var ENDPOINTS = {
  docs: "/api/mcp/docs",
  cli: "/api/mcp/cli",
  internal: "/api/mcp/internal",
  graphql: "/graphql",
  health: "/health"
};
function buildInternalResources() {
  const resources = new ResourceRegistry3;
  resources.register(defineResourceTemplate3({
    meta: {
      uriTemplate: "examples://list{?q}",
      title: "ContractSpec examples registry",
      description: "List available examples (templates, integrations, knowledge, scripts). Optional query `q` filters results.",
      mimeType: "application/json",
      tags: ["examples", ...INTERNAL_TAGS]
    },
    input: z3.object({ q: z3.string().optional() }),
    resolve: async ({ q }) => {
      const items = q ? searchExamples(q) : [...listExamples()];
      return {
        uri: q ? `examples://list?q=${encodeURIComponent(q)}` : "examples://list",
        mimeType: "application/json",
        data: JSON.stringify(items, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate3({
    meta: {
      uriTemplate: "examples://example/{id}",
      title: "ContractSpec example (by id)",
      description: "Fetch a single example manifest by id.",
      mimeType: "application/json",
      tags: ["examples", ...INTERNAL_TAGS]
    },
    input: z3.object({ id: z3.string().min(1) }),
    resolve: async ({ id }) => {
      const example = getExample(id);
      if (!example) {
        return {
          uri: `examples://example/${encodeURIComponent(id)}`,
          mimeType: "application/json",
          data: JSON.stringify({ error: "not_found", id, message: `Unknown example id: ${id}` }, null, 2)
        };
      }
      return {
        uri: `examples://example/${encodeURIComponent(id)}`,
        mimeType: "application/json",
        data: JSON.stringify(example, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate3({
    meta: {
      uriTemplate: "internal://endpoints",
      title: "ContractSpec MCP endpoints",
      description: "Endpoints for docs, CLI, internal MCP servers.",
      mimeType: "application/json",
      tags: INTERNAL_TAGS
    },
    input: z3.object({}),
    resolve: async () => ({
      uri: "internal://endpoints",
      mimeType: "application/json",
      data: JSON.stringify(ENDPOINTS, null, 2)
    })
  }));
  resources.register(defineResourceTemplate3({
    meta: {
      uriTemplate: "internal://playbook",
      title: "Internal MCP usage playbook",
      description: "How internal agents should discover docs, CLI usage, and endpoints.",
      mimeType: "text/markdown",
      tags: INTERNAL_TAGS
    },
    input: z3.object({}),
    resolve: async () => ({
      uri: "internal://playbook",
      mimeType: "text/markdown",
      data: [
        "# Internal MCP playbook",
        "- Connect to docs MCP first for canonical specs.",
        "- Use CLI MCP to surface quickstart/reference before running commands.",
        "- Keep calls read-only unless explicitly approved.",
        `- Endpoints: ${ENDPOINTS.docs}, ${ENDPOINTS.cli}, ${ENDPOINTS.internal}.`,
        "- For API work, GraphQL at /graphql; health at /health."
      ].join(`
`)
    })
  }));
  return resources;
}
function buildInternalPrompts() {
  const prompts = new PromptRegistry3;
  prompts.register(definePrompt3({
    meta: {
      key: "internal.bootstrap",
      version: "1.0.0",
      title: "Bootstrap internal ContractSpec agent",
      description: "Points agents to the correct MCP endpoints and guardrails.",
      tags: INTERNAL_TAGS,
      owners: INTERNAL_OWNERS,
      stability: "beta"
    },
    args: [],
    input: z3.object({}),
    render: async () => [
      {
        type: "text",
        text: "Start with internal://endpoints to pick the right MCP. Use docs MCP for specifications and CLI MCP for commands. Keep actions read-only unless explicitly approved."
      },
      {
        type: "resource",
        uri: "internal://endpoints",
        title: "Endpoints"
      }
    ]
  }));
  return prompts;
}
function buildInternalOps() {
  const registry = new OperationSpecRegistry3;
  const InternalDescribeOutput = defineSchemaModel2({
    name: "InternalDescribeOutput",
    fields: {
      endpoints: {
        type: ScalarTypeEnum2.JSONObject(),
        isOptional: false
      },
      notes: { type: ScalarTypeEnum2.String_unsecure(), isOptional: false }
    }
  });
  const describeSpec = defineCommand2({
    meta: {
      key: "internal.describe",
      version: "1.0.0",
      stability: "stable",
      owners: INTERNAL_OWNERS,
      tags: INTERNAL_TAGS,
      description: "Return MCP endpoints and guidance for internal ContractSpec agents.",
      goal: "Speed up internal development with the correct MCP entrypoints.",
      context: "Used by internal MCP surface; read-only."
    },
    io: {
      input: defineSchemaModel2({
        name: "InternalDescribeInput",
        fields: {}
      }),
      output: InternalDescribeOutput
    },
    policy: {
      auth: "anonymous"
    }
  });
  installOp3(registry, describeSpec, async () => ({
    endpoints: ENDPOINTS,
    notes: "Use docs MCP for canonical specs, CLI MCP for contractspec commands, and keep side-effecting actions gated behind human review."
  }));
  return registry;
}
function createInternalMcpHandler(path2 = "/api/mcp/internal") {
  return createMcpElysiaHandler({
    logger: appLogger,
    path: path2,
    serverName: "contractspec-internal-mcp",
    ops: buildInternalOps(),
    resources: buildInternalResources(),
    prompts: buildInternalPrompts()
  });
}

// src/application/mcp/providerRankingMcp.ts
import {
  definePrompt as definePrompt4,
  defineResourceTemplate as defineResourceTemplate4,
  installOp as installOp4,
  OperationSpecRegistry as OperationSpecRegistry4,
  PromptRegistry as PromptRegistry4,
  ResourceRegistry as ResourceRegistry4
} from "@contractspec/lib.contracts-spec";
import {
  BenchmarkIngestCommand,
  BenchmarkRunCustomCommand,
  RankingRefreshCommand
} from "@contractspec/lib.contracts-spec/provider-ranking";
import z4 from "zod";
import { InMemoryProviderRankingStore } from "@contractspec/lib.provider-ranking/in-memory-store";
import { createDefaultIngesterRegistry } from "@contractspec/lib.provider-ranking/ingesters";
import { computeModelRankings } from "@contractspec/lib.provider-ranking/scoring";
import { normalizeBenchmarkResults } from "@contractspec/lib.provider-ranking/scoring";
var TransportFilterSchema = z4.enum(["rest", "mcp", "webhook", "sdk"]).optional();
var AuthFilterSchema = z4.enum([
  "api-key",
  "oauth2",
  "bearer",
  "header",
  "basic",
  "webhook-signing",
  "service-account"
]).optional();
var RANKING_TAGS = ["ranking", "mcp", "ai"];
var RANKING_OWNERS = ["platform.ai"];
var sharedStore = null;
function getStore() {
  if (!sharedStore) {
    sharedStore = new InMemoryProviderRankingStore;
  }
  return sharedStore;
}
function buildRankingResources() {
  const resources = new ResourceRegistry4;
  resources.register(defineResourceTemplate4({
    meta: {
      uriTemplate: "ranking://leaderboard",
      title: "AI Model Leaderboard",
      description: "Current ranked list of AI models by composite score. Supports optional transport and authMethod query filters.",
      mimeType: "application/json",
      tags: RANKING_TAGS
    },
    input: z4.object({
      transport: TransportFilterSchema,
      authMethod: AuthFilterSchema
    }),
    resolve: async ({ transport, authMethod }) => {
      const store = getStore();
      const result = await store.listModelRankings({
        limit: 100,
        requiredTransport: transport,
        requiredAuthMethod: authMethod
      });
      return {
        uri: "ranking://leaderboard",
        mimeType: "application/json",
        data: JSON.stringify(result, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate4({
    meta: {
      uriTemplate: "ranking://leaderboard/{dimension}",
      title: "AI Model Leaderboard by Dimension",
      description: "Ranked list of AI models filtered by a specific dimension. Supports optional transport and authMethod query filters.",
      mimeType: "application/json",
      tags: RANKING_TAGS
    },
    input: z4.object({
      dimension: z4.string(),
      transport: TransportFilterSchema,
      authMethod: AuthFilterSchema
    }),
    resolve: async ({ dimension, transport, authMethod }) => {
      const store = getStore();
      const result = await store.listModelRankings({
        dimension,
        limit: 100,
        requiredTransport: transport,
        requiredAuthMethod: authMethod
      });
      return {
        uri: `ranking://leaderboard/${encodeURIComponent(dimension)}`,
        mimeType: "application/json",
        data: JSON.stringify(result, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate4({
    meta: {
      uriTemplate: "ranking://model/{modelId}",
      title: "AI Model Profile",
      description: "Detailed profile for a specific AI model including scores and benchmarks.",
      mimeType: "application/json",
      tags: RANKING_TAGS
    },
    input: z4.object({ modelId: z4.string() }),
    resolve: async ({ modelId }) => {
      const store = getStore();
      const profile = await store.getModelProfile(modelId);
      if (!profile) {
        return {
          uri: `ranking://model/${encodeURIComponent(modelId)}`,
          mimeType: "application/json",
          data: JSON.stringify({ error: "not_found", modelId })
        };
      }
      return {
        uri: `ranking://model/${encodeURIComponent(modelId)}`,
        mimeType: "application/json",
        data: JSON.stringify(profile, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate4({
    meta: {
      uriTemplate: "ranking://results",
      title: "Benchmark Results",
      description: "List of raw benchmark results from all ingested sources.",
      mimeType: "application/json",
      tags: RANKING_TAGS
    },
    input: z4.object({}),
    resolve: async () => {
      const store = getStore();
      const result = await store.listBenchmarkResults({ limit: 200 });
      return {
        uri: "ranking://results",
        mimeType: "application/json",
        data: JSON.stringify(result, null, 2)
      };
    }
  }));
  return resources;
}
function buildRankingPrompts() {
  const prompts = new PromptRegistry4;
  prompts.register(definePrompt4({
    meta: {
      key: "ranking.advisor",
      version: "1.0.0",
      title: "AI Model Advisor",
      description: "Which AI model is best for a given task? Uses the leaderboard to recommend.",
      tags: RANKING_TAGS,
      stability: "beta",
      owners: RANKING_OWNERS
    },
    args: [
      {
        name: "task",
        description: "The task or use case to recommend a model for.",
        required: true,
        schema: z4.string()
      },
      {
        name: "priority",
        description: "Priority dimension (coding, reasoning, cost, latency, etc.).",
        required: false,
        schema: z4.string().optional()
      },
      {
        name: "transport",
        description: "Required transport type (rest, mcp, webhook, sdk).",
        required: false,
        schema: TransportFilterSchema
      },
      {
        name: "authMethod",
        description: "Required auth method (api-key, oauth2, bearer, etc.).",
        required: false,
        schema: AuthFilterSchema
      }
    ],
    input: z4.object({
      task: z4.string(),
      priority: z4.string().optional(),
      transport: TransportFilterSchema,
      authMethod: AuthFilterSchema
    }),
    render: async ({ task, priority, transport, authMethod }) => {
      const constraints = [];
      if (priority)
        constraints.push(`Prioritize: ${priority}.`);
      if (transport)
        constraints.push(`Required transport: ${transport}.`);
      if (authMethod)
        constraints.push(`Required auth: ${authMethod}.`);
      return [
        {
          type: "text",
          text: `Recommend the best AI model for: "${task}".${constraints.length ? ` ${constraints.join(" ")}` : ""} Use the leaderboard data to justify your recommendation.`
        },
        {
          type: "resource",
          uri: priority ? `ranking://leaderboard/${priority}` : "ranking://leaderboard",
          title: "Leaderboard"
        }
      ];
    }
  }));
  return prompts;
}
function buildRankingOps() {
  const registry = new OperationSpecRegistry4;
  const ingesterRegistry = createDefaultIngesterRegistry();
  installOp4(registry, BenchmarkIngestCommand, async (args) => {
    const store = getStore();
    const source = args.source;
    const ingester = ingesterRegistry.get(source);
    if (!ingester) {
      throw new Error(`No ingester registered for source: ${source}`);
    }
    const rawResults = await ingester.ingest({
      sourceUrl: args.sourceUrl,
      dimensions: args.dimensions
    });
    const normalized = normalizeBenchmarkResults(rawResults);
    for (const result of normalized) {
      await store.upsertBenchmarkResult(result);
    }
    return {
      ingestionId: `ingest-${source}-${Date.now()}`,
      source,
      resultsCount: normalized.length,
      status: "completed",
      ingestedAt: new Date
    };
  });
  installOp4(registry, BenchmarkRunCustomCommand, async (args) => {
    return {
      runId: `custom-${Date.now()}`,
      evalSuiteKey: args.evalSuiteKey,
      modelId: args.modelId,
      status: "started",
      startedAt: new Date
    };
  });
  installOp4(registry, RankingRefreshCommand, async (args) => {
    const store = getStore();
    const allResults = [];
    let offset = 0;
    const pageSize = 500;
    while (true) {
      const page = await store.listBenchmarkResults({
        limit: pageSize,
        offset
      });
      allResults.push(...page.results);
      if (allResults.length >= page.total || page.results.length < pageSize)
        break;
      offset += pageSize;
    }
    const existingRankings = new Map((await store.listModelRankings({ limit: 1e4 })).rankings.map((r) => [
      r.modelId,
      r
    ]));
    const weightOverrides = args.weightOverrides ? Array.isArray(args.weightOverrides) ? args.weightOverrides : [args.weightOverrides] : undefined;
    const newRankings = computeModelRankings(allResults, weightOverrides ? {
      weightOverrides
    } : undefined, existingRankings);
    for (const ranking of newRankings) {
      await store.upsertModelRanking(ranking);
    }
    return {
      modelsRanked: newRankings.length,
      updatedAt: new Date,
      status: "completed"
    };
  });
  return registry;
}
function createProviderRankingMcpHandler(path2 = "/api/mcp/ranking") {
  return createMcpElysiaHandler({
    logger: appLogger,
    path: path2,
    serverName: "contractspec-ranking-mcp",
    ops: buildRankingOps(),
    resources: buildRankingResources(),
    prompts: buildRankingPrompts()
  });
}
function setProviderRankingStore(store) {
  sharedStore = store;
}

// src/application/mcp/contractsMcpTools.ts
import {
  defineCommand as defineCommand3,
  installOp as installOp5,
  OperationSpecRegistry as OperationSpecRegistry5
} from "@contractspec/lib.contracts-spec";
import { defineSchemaModel as defineSchemaModel3, ScalarTypeEnum as ScalarTypeEnum3 } from "@contractspec/lib.schema";
var OWNERS = ["@contractspec"];
var TAGS = ["contracts", "mcp"];
function buildContractsOps(services) {
  const registry = new OperationSpecRegistry5;
  const ListInput = defineSchemaModel3({
    name: "ContractsListInput",
    fields: {
      pattern: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
      type: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true }
    }
  });
  const ListOutput = defineSchemaModel3({
    name: "ContractsListOutput",
    fields: {
      specs: { type: ScalarTypeEnum3.JSON(), isOptional: false },
      total: { type: ScalarTypeEnum3.Int_unsecure(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.list",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "List contract specs in the workspace.",
      goal: "Discover available contracts by type, pattern, or owner.",
      context: "Contracts MCP server."
    },
    io: { input: ListInput, output: ListOutput },
    policy: { auth: "anonymous" }
  }), async ({ pattern, type }) => {
    const specs = await services.listSpecs({ pattern, type });
    return { specs, total: specs.length };
  });
  const GetInput = defineSchemaModel3({
    name: "ContractsGetInput",
    fields: {
      path: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
    }
  });
  const GetOutput = defineSchemaModel3({
    name: "ContractsGetOutput",
    fields: {
      content: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
      info: { type: ScalarTypeEnum3.JSON(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.get",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "Read a single contract spec file.",
      goal: "Fetch spec content and parsed metadata.",
      context: "Contracts MCP server."
    },
    io: { input: GetInput, output: GetOutput },
    policy: { auth: "anonymous" }
  }), async ({ path: path2 }) => {
    const result = await services.getSpec(path2);
    if (!result)
      throw new Error(`Spec not found: ${path2}`);
    return result;
  });
  const ValidateInput = defineSchemaModel3({
    name: "ContractsValidateInput",
    fields: {
      path: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false }
    }
  });
  const ValidateOutput = defineSchemaModel3({
    name: "ContractsValidateOutput",
    fields: {
      valid: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
      errors: { type: ScalarTypeEnum3.JSON(), isOptional: false },
      warnings: { type: ScalarTypeEnum3.JSON(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.validate",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "Validate a contract spec structure.",
      goal: "Check spec for structural or policy issues.",
      context: "Contracts MCP server."
    },
    io: { input: ValidateInput, output: ValidateOutput },
    policy: { auth: "anonymous" }
  }), async ({ path: path2 }) => services.validateSpec(path2));
  const BuildInput = defineSchemaModel3({
    name: "ContractsBuildInput",
    fields: {
      path: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
      dryRun: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
    }
  });
  const BuildOutput = defineSchemaModel3({
    name: "ContractsBuildOutput",
    fields: {
      results: { type: ScalarTypeEnum3.JSON(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.build",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "Generate implementation code from a contract spec.",
      goal: "Produce handler, component, or test skeletons.",
      context: "Contracts MCP server."
    },
    io: { input: BuildInput, output: BuildOutput },
    policy: { auth: "user" }
  }), async ({ path: path2, dryRun }) => services.buildSpec(path2, { dryRun }));
  registerMutationTools(registry, services);
  return registry;
}
function registerMutationTools(registry, services) {
  const UpdateInput = defineSchemaModel3({
    name: "ContractsUpdateInput",
    fields: {
      path: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
      content: { type: ScalarTypeEnum3.String_unsecure(), isOptional: true },
      fields: { type: ScalarTypeEnum3.JSON(), isOptional: true }
    }
  });
  const UpdateOutput = defineSchemaModel3({
    name: "ContractsUpdateOutput",
    fields: {
      updated: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
      errors: { type: ScalarTypeEnum3.JSON(), isOptional: false },
      warnings: { type: ScalarTypeEnum3.JSON(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.update",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "Update an existing contract spec.",
      goal: "Modify spec content or individual fields with validation.",
      context: "Contracts MCP server."
    },
    io: { input: UpdateInput, output: UpdateOutput },
    policy: { auth: "user" }
  }), async ({ path: path2, content, fields }) => services.updateSpec(path2, {
    content,
    fields: Array.isArray(fields) ? fields : undefined
  }));
  const DeleteInput = defineSchemaModel3({
    name: "ContractsDeleteInput",
    fields: {
      path: { type: ScalarTypeEnum3.String_unsecure(), isOptional: false },
      clean: { type: ScalarTypeEnum3.Boolean(), isOptional: true }
    }
  });
  const DeleteOutput = defineSchemaModel3({
    name: "ContractsDeleteOutput",
    fields: {
      deleted: { type: ScalarTypeEnum3.Boolean(), isOptional: false },
      cleanedFiles: { type: ScalarTypeEnum3.JSON(), isOptional: false },
      errors: { type: ScalarTypeEnum3.JSON(), isOptional: false }
    }
  });
  installOp5(registry, defineCommand3({
    meta: {
      key: "contracts.delete",
      version: "1.0.0",
      stability: "beta",
      owners: OWNERS,
      tags: TAGS,
      description: "Delete a contract spec and optionally its artifacts.",
      goal: "Remove a spec file and clean generated handlers/tests.",
      context: "Contracts MCP server."
    },
    io: { input: DeleteInput, output: DeleteOutput },
    policy: { auth: "user" }
  }), async ({ path: path2, clean }) => services.deleteSpec(path2, { clean }));
}

// src/application/mcp/contractsMcpResources.ts
import {
  definePrompt as definePrompt5,
  defineResourceTemplate as defineResourceTemplate5,
  PromptRegistry as PromptRegistry5,
  ResourceRegistry as ResourceRegistry5
} from "@contractspec/lib.contracts-spec";
import z5 from "zod";
var OWNERS2 = ["@contractspec"];
var TAGS2 = ["contracts", "mcp"];
function buildContractsResources(services) {
  const resources = new ResourceRegistry5;
  resources.register(defineResourceTemplate5({
    meta: {
      uriTemplate: "contracts://list",
      title: "Contract specs list",
      description: "JSON list of all contract specs in the workspace.",
      mimeType: "application/json",
      tags: TAGS2
    },
    input: z5.object({}),
    resolve: async () => {
      const specs = await services.listSpecs();
      return {
        uri: "contracts://list",
        mimeType: "application/json",
        data: JSON.stringify(specs, null, 2)
      };
    }
  }));
  resources.register(defineResourceTemplate5({
    meta: {
      uriTemplate: "contracts://spec/{path}",
      title: "Contract spec content",
      description: "Read a single contract spec file by path.",
      mimeType: "text/plain",
      tags: TAGS2
    },
    input: z5.object({ path: z5.string() }),
    resolve: async ({ path: path2 }) => {
      const result = await services.getSpec(path2);
      if (!result) {
        return {
          uri: `contracts://spec/${encodeURIComponent(path2)}`,
          mimeType: "text/plain",
          data: `Spec not found: ${path2}`
        };
      }
      return {
        uri: `contracts://spec/${encodeURIComponent(path2)}`,
        mimeType: "text/plain",
        data: result.content
      };
    }
  }));
  resources.register(defineResourceTemplate5({
    meta: {
      uriTemplate: "contracts://registry/manifest",
      title: "Remote registry manifest",
      description: "Contract registry manifest from the remote server.",
      mimeType: "application/json",
      tags: TAGS2
    },
    input: z5.object({}),
    resolve: async () => {
      const manifest = await services.fetchRegistryManifest();
      return {
        uri: "contracts://registry/manifest",
        mimeType: "application/json",
        data: JSON.stringify(manifest, null, 2)
      };
    }
  }));
  return resources;
}
function buildContractsPrompts() {
  const prompts = new PromptRegistry5;
  prompts.register(definePrompt5({
    meta: {
      key: "contracts.editor",
      version: "1.0.0",
      title: "Contract editing guide",
      description: "Guide AI agents through reading, editing, and validating contracts.",
      tags: TAGS2,
      stability: "beta",
      owners: OWNERS2
    },
    args: [
      {
        name: "goal",
        description: "What the agent wants to achieve with the contract.",
        required: false,
        schema: z5.string().optional()
      }
    ],
    input: z5.object({ goal: z5.string().optional() }),
    render: async ({ goal }) => [
      {
        type: "text",
        text: [
          "Contract editing workflow:",
          "1. Use contracts.list to discover specs",
          "2. Use contracts.get to read a spec",
          "3. Edit content and call contracts.update",
          "4. Run contracts.validate to verify changes",
          "5. Run contracts.build to regenerate artifacts",
          goal ? `Agent goal: ${goal}` : ""
        ].filter(Boolean).join(`
`)
      },
      {
        type: "resource",
        uri: "contracts://list",
        title: "Available contracts"
      }
    ]
  }));
  return prompts;
}

// src/application/mcp/contractsMcp.ts
function createContractsMcpHandler(path2 = "/api/mcp/contracts", services) {
  return createMcpElysiaHandler({
    logger: appLogger,
    path: path2,
    serverName: "contractspec-contracts-mcp",
    ops: buildContractsOps(services),
    resources: buildContractsResources(services),
    prompts: buildContractsPrompts()
  });
}
export {
  setProviderRankingStore,
  createProviderRankingMcpHandler,
  createInternalMcpHandler,
  createDocsMcpHandler,
  createContractsMcpHandler,
  createContextStorageService,
  createCliMcpHandler
};
