/**
 * studiograph mcp
 *
 * Starts the Studiograph MCP server for integration with Claude Desktop
 * and other MCP-compatible clients.
 *
 * The server communicates over stdio (JSON-RPC). Claude Desktop spawns this
 * process and communicates directly — no HTTP port is opened.
 *
 * Claude Desktop config (~/.config/Claude/claude_desktop_config.json or
 * ~/Library/Application Support/Claude/claude_desktop_config.json):
 *
 *   {
 *     "mcpServers": {
 *       "studiograph": {
 *         "command": "studiograph",
 *         "args": ["mcp"],
 *         "cwd": "/absolute/path/to/your/workspace"
 *       }
 *     }
 *   }
 *
 * NOTE: Do not use console.log() in this process — stdout is owned by the
 * MCP protocol. Use console.error() for any diagnostic output.
 */
import { Command } from 'commander';
import { Workspace } from '../../core/workspace.js';
import { WorkspaceManager } from '../../core/workspace-manager.js';
import { loadUserConfig } from '../../core/user-config.js';
import { tryResolve } from '../../core/secrets/read-flip.js';
import { AuthService } from '../../services/auth-service.js';
import { startMcpServer } from '../../mcp/server.js';
export const mcpCommand = new Command('mcp')
    .description('Start the Studiograph MCP server for Claude Desktop integration')
    .argument('[workspace]', 'Path to workspace (defaults to current directory)')
    .action(async (workspaceArg) => {
    const workspacePath = workspaceArg ?? process.cwd();
    const workspace = new Workspace(workspacePath);
    if (!workspace.isWorkspace()) {
        process.stderr.write('Not a Studiograph workspace.\n' +
            'Run `studiograph init` first, or pass the workspace path: studiograph mcp /path/to/workspace\n');
        process.exit(1);
    }
    const config = await workspace.loadConfig();
    // Propagate Anthropic API key from store (Phase 6) or user config
    // if not already set. The store wins over user.json — post Phase 6,
    // user.json is no longer authoritative for credentials. The MCP CLI
    // assumes Anthropic since it's the original use case; if you've
    // switched providers, set ANTHROPIC_API_KEY in your shell manually.
    const userConfig = loadUserConfig();
    const apiKey = tryResolve('model.anthropic.api_key') ?? userConfig.api_key;
    if (apiKey && !process.env.ANTHROPIC_API_KEY) {
        process.env.ANTHROPIC_API_KEY = apiKey;
    }
    // MCP uses a service identity for git commits made via create/update tools
    const gitUser = {
        id: 'mcp',
        name: 'Studiograph MCP',
        email: 'noreply@studiograph.local',
    };
    const workspaceManager = new WorkspaceManager(workspacePath, config, gitUser);
    const authService = new AuthService(workspacePath);
    await startMcpServer(workspaceManager, authService);
});
//# sourceMappingURL=mcp.js.map