All files / cli mcp-cli.command.ts

100% Statements 66/66
87.5% Branches 21/24
100% Functions 11/11
100% Lines 64/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 3002x 2x 2x 2x                                           2x   129x 129x   129x                 2x 1x                 2x 1x                 2x 1x             2x 1x                 19x           19x 15x 15x 12x   12x 10x     3x                   3x 3x 1x 1x 1x               19x 12x       19x           25x   25x     25x     5x                   5x       2x                                                                           2x       8x   8x     8x   2x               2x     4x   4x 2x           2x           4x               4x       2x                 6x       4x 2x     4x 4x 3x           1x           3x       2x                   18x   3x                         13x 13x        
import { Command, CommandRunner, Option } from 'nest-commander';
import { SquadService } from '../core/mcp';
import { SquadConfigService } from '../core/config';
import * as readline from 'readline';
 
interface IMcpRequest {
  method: string;
  params?: Record<string, unknown>;
  id?: string | number;
}
 
interface IMcpResponse {
  jsonrpc: '2.0';
  result?: unknown;
  error?: {
    code: number;
    message: string;
  };
  id?: string | number;
}
 
@Command({
  name: 'mcp',
  description: 'Squad MCP stdio server'
})
export class McpCliCommand extends CommandRunner {
  constructor(
    private readonly squadService: SquadService,
    private readonly configService: SquadConfigService
  ) {
    super();
  }
 
  // Accept CLI options (nest-commander)
  // Config also parses process.argv (options are optional).
  @Option({
    flags: '--engine <engine>',
    description: 'Engine to use: cursor-agent | claude | codex'
  })
  parseEngine(value: string): string {
    return value;
  }
 
  @Option({
    flags: '--execution-mode <mode>',
    description:
      'Execution mode when using a custom template: ' +
      'sequential | parallel'
  })
  parseExecutionMode(value: string): string {
    return value;
  }
 
  @Option({
    flags: '--sequential',
    description:
      'Shorthand to force sequential execution ' +
      'when using a custom template'
  })
  parseSequential(): boolean {
    return true;
  }
 
  @Option({
    flags: '--state-mode <mode>',
    description: 'State mode: stateless | stateful'
  })
  parseStateMode(value: string): string {
    return value;
  }
 
  async run(
    _passedParams?: string[],
    _options?: Record<string, unknown>
  ): Promise<void> {
    // Use stderr for readline output to
    // avoid interfering with JSON-RPC on stdout
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stderr,
      terminal: false
    });
 
    rl.on('line', async (line: string) => {
      try {
        const request: IMcpRequest = JSON.parse(line);
        const response = await this.handleRequest(request);
        // Only send response if it has an id (not a notification)
        if (response.id !== undefined) {
          this.sendResponse(response);
        }
      } catch (error) {
        const errorResponse: IMcpResponse = {
          jsonrpc: '2.0',
          error: {
            code: -32700,
            message:
              error instanceof Error ? error.message : 'Parse error'
          },
          id: undefined // Parse errors should include id if request had one
        };
        // Try to extract id from the original request if possible
        try {
          const request: IMcpRequest = JSON.parse(line);
          Eif (request.id !== undefined) {
            errorResponse.id = request.id;
            this.sendResponse(errorResponse);
          }
        } catch {
          // If we can't parse, don't send response
        }
      }
    });
 
    rl.on('close', () => {
      process.exit(0);
    });
 
    // Keep process alive
    await new Promise(() => {});
  }
 
  private async handleRequest(
    request: IMcpRequest
  ): Promise<IMcpResponse> {
    const { method, params = {}, id } = request;
 
    try {
      let result: unknown;
 
      switch (method) {
        case 'initialize':
          // MCP protocol initialization
          result = {
            protocolVersion: '2024-11-05',
            capabilities: {
              tools: {}
            },
            serverInfo: {
              name: 'gs-squad-mcp',
              version: '1.0.2'
            }
          };
          break;
 
        case 'tools/list':
          // Return available MCP tools
          result = {
            tools: [
              {
                name: 'list_roles',
                description: 'List all available role definitions',
                inputSchema: {
                  type: 'object',
                  properties: {},
                  required: []
                }
              },
              {
                name: 'start_squad_members',
                description: 'Spawn one or more role-specialized agents',
                inputSchema: {
                  type: 'object',
                  properties: {
                    orchestratorChatId: { type: 'string' },
                    workspaceId: { type: 'string' },
                    members: {
                      type: 'array',
                      items: {
                        type: 'object',
                        properties: {
                          roleId: { type: 'string' },
                          task: { type: 'string' },
                          cwd: { type: 'string' },
                          chatId: { type: 'string' }
                        },
                        required: [ 'roleId', 'task' ]
                      }
                    }
                  },
                  required: [ 'members' ]
                }
              }
            ]
          };
          break;
 
        case 'tools/call': {
          // MCP protocol tool invocation
          const toolName = (params as { name?: string }).name;
          const toolArguments = 
            (params as { arguments?: Record<string, unknown> })
              .arguments || {};
 
          switch (toolName) {
            case 'list_roles':
              result = {
                content: [
                  {
                    type: 'text',
                    text: JSON.stringify(await this.squadService.listRoles())
                  }
                ]
              };
              break;
 
            case 'start_squad_members': {
              const config = this.configService.getConfig();
              let toolResult: unknown;
              if (config.stateMode === 'stateless') {
                toolResult = await this.squadService.startSquadMembersStateless(
                  toolArguments as unknown as Parameters<
                    typeof this.squadService.startSquadMembersStateless
                  >[0]
                );
              } else {
                toolResult = await this.squadService.startSquadMembersStateful(
                  toolArguments as unknown as Parameters<
                    typeof this.squadService.startSquadMembersStateful
                  >[0]
                );
              }
              result = {
                content: [
                  {
                    type: 'text',
                    text: JSON.stringify(toolResult)
                  }
                ]
              };
              break;
            }
 
            default:
              return {
                jsonrpc: '2.0',
                error: {
                  code: -32601,
                  message: `Tool not found: ${toolName}`
                },
                id
              };
          }
          break;
        }
 
        case 'list_roles':
          result = await this.squadService.listRoles();
          break;
 
        case 'start_squad_members': {
          const config = this.configService.getConfig();
          if (config.stateMode === 'stateless') {
            result = await this.squadService.startSquadMembersStateless(
              params as unknown as Parameters<
                typeof this.squadService.startSquadMembersStateless
              >[0]
            );
          } else {
            result = await this.squadService.startSquadMembersStateful(
              params as unknown as Parameters<
                typeof this.squadService.startSquadMembersStateful
              >[0]
            );
          }
          break;
        }
 
        default:
          return {
            jsonrpc: '2.0',
            error: {
              code: -32601,
              message: `Method not found: ${method}`
          },
          id
        };
      }
 
      return { jsonrpc: '2.0', result, id };
    } catch (error) {
      return {
        jsonrpc: '2.0',
        error: {
          code: -32603,
          message:
            error instanceof Error ? error.message : 'Internal error'
        },
        id
      };
    }
  }
 
  private sendResponse(response: IMcpResponse): void {
    const json = JSON.stringify(response);
    process.stdout.write(json + '\n');
  }
}