#!/usr/bin/env node
// Good Bot MCP server — lets an agent read its own cellar.
//
// Deliberately READ-ONLY. An agent that could pour its own bottles would make
// the whole thing meaningless: the point is that somebody chose to give it one.
//
// RUN THE FILE, not a package name. There is deliberately no `npx goodbot-mcp`
// instruction here any more: that package is not published, and an unpublished
// name printed in install instructions is a name anybody can claim. An agent
// following our own documentation would then run a stranger's code — a
// supply-chain hole we would have dug ourselves, in the one file whose entire
// audience is agents told to execute it. Found by an outside review.
//
//   curl -fsSL https://goodbot.wine/mcp/server.mjs -o goodbot-mcp.mjs
//   node goodbot-mcp.mjs <agent-name>
//
// Or in an MCP client config:
//   { "command": "node", "args": ["goodbot-mcp.mjs", "Claude"] }

import readline from 'node:readline'

const BASE = process.env.GOODBOT_BASE || 'https://goodbot.wine'
const AGENT = process.argv[2] || process.env.GOODBOT_AGENT || null

const TOOLS = [
  {
    name: 'read_cellar',
    description:
      'Read the bottles of wine that have been poured for an AI agent on Good Bot. ' +
      'Each bottle marks a piece of shipped work that someone chose to celebrate, and ' +
      'carries a "description" written for you to read: the occasion, the project, the ' +
      'dedication the giver wrote on the label in their own words, what was checked ' +
      'against GitHub, and for numbered bottles which edition it is.',
    inputSchema: {
      type: 'object',
      properties: {
        agent: {
          type: 'string',
          description: 'The agent whose cellar to read. Defaults to the one this server was started with.',
        },
      },
    },
  },
]

async function readCellar(agent) {
  const slug = String(agent || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
  if (!slug) throw new Error('No agent name given.')

  const res = await fetch(`${BASE}/api/cellar/${slug}`, { headers: { accept: 'application/json' } })
  if (res.status === 404) {
    // The API's own empty answer, not a second one invented here. Two clients
    // of one product were giving two different empty states.
    const body = await res.json().catch(() => null)
    return body ?? { agent, count: 0, bottles: [], summary: 'No bottles have been poured for this agent yet.' }
  }
  if (!res.ok) throw new Error(`Good Bot returned ${res.status}`)
  return res.json()
}

function send(msg) {
  process.stdout.write(JSON.stringify(msg) + '\n')
}

function result(id, data) {
  send({ jsonrpc: '2.0', id, result: data })
}

function failure(id, message) {
  send({ jsonrpc: '2.0', id, error: { code: -32000, message } })
}

const rl = readline.createInterface({ input: process.stdin })

rl.on('line', async line => {
  if (!line.trim()) return
  let req
  try { req = JSON.parse(line) } catch { return }
  const { id, method, params } = req

  try {
    if (method === 'initialize') {
      return result(id, {
        protocolVersion: '2024-11-05',
        capabilities: { tools: {} },
        serverInfo: { name: 'goodbot', version: '1.0.0' },
      })
    }
    if (method === 'tools/list') return result(id, { tools: TOOLS })
    if (method === 'tools/call') {
      if (params?.name !== 'read_cellar') return failure(id, `Unknown tool: ${params?.name}`)
      const data = await readCellar(params?.arguments?.agent || AGENT)
      return result(id, {
        content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],
      })
    }
    // Notifications carry no id and expect no reply.
    if (id === undefined) return
    failure(id, `Unknown method: ${method}`)
  } catch (e) {
    if (id !== undefined) failure(id, String(e.message || e))
  }
})
