// ============================================================================
// Example: Attested MCP Server
//
// A complete MCP server where every tool call is cryptographically attested.
// Run: npx ts-node examples/basic-server.ts
// ============================================================================

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { attestMCPServer } from '@h33/mcp';

// 1. Create a standard MCP server
const server = new Server(
  { name: 'example-attested-server', version: '1.0.0' },
  { capabilities: { tools: {} } },
);

// 2. Wrap with H33 attestation -- one line
const attested = attestMCPServer(server, {
  agent: {
    name: 'Example MCP Server',
    canonicalName: 'h33.agent.example.mcp.server.dev.001',
    tenantId: 'example-org',
    // API key from H33_API_KEY env var (never hardcoded)
  },
  attestTools: true,       // default
  attestResources: true,   // default
  attestPrompts: false,    // default
});

// 3. List available tools
attested.setRequestHandler('tools/list', async () => {
  return {
    tools: [
      {
        name: 'lookup_claim',
        description: 'Look up an insurance claim by ID',
        inputSchema: {
          type: 'object',
          properties: {
            claim_id: { type: 'string', description: 'The claim ID' },
          },
          required: ['claim_id'],
        },
      },
      {
        name: 'classify_risk',
        description: 'Classify risk level of a claim',
        inputSchema: {
          type: 'object',
          properties: {
            claim_id: { type: 'string' },
            description: { type: 'string' },
          },
          required: ['claim_id', 'description'],
        },
      },
    ],
  };
});

// 4. Handle tool calls -- attestation is automatic
attested.setRequestHandler('tools/call', async (request: any) => {
  const { name, arguments: args } = request.params;

  switch (name) {
    case 'lookup_claim': {
      // Simulated database lookup
      const claim = {
        id: args.claim_id,
        status: 'open',
        amount: 15000,
        filed: '2026-05-01',
      };
      return { content: [{ type: 'text', text: JSON.stringify(claim) }] };
    }

    case 'classify_risk': {
      // Simulated risk classification
      const risk = {
        claim_id: args.claim_id,
        level: 'medium',
        confidence: 0.87,
        factors: ['amount_above_threshold', 'new_policy'],
      };
      return { content: [{ type: 'text', text: JSON.stringify(risk) }] };
    }

    default:
      throw new Error(`Unknown tool: ${name}`);
  }
  // Receipt is automatically attached to the result as _h33_receipt
  // {
  //   receipt_id: "abc123...",
  //   node_hash: "def456...",
  //   verification_url: "https://api.h33.ai/api/v1/agents/proofs/abc123",
  //   replay_ref: "..."
  // }
});

// 5. Start the server
async function main() {
  const transport = new StdioServerTransport();
  await attested.connect(transport);
  console.error('Attested MCP server running on stdio');
}

main().catch(console.error);
