### Initialize MCPCodex Project Source: https://docs.mcpcodex.ca/getting-started/quickstart Creates a new MCPCodex project using the interactive setup wizard, navigates into the project directory, and installs the necessary project dependencies. This sets up the environment for further development. ```bash # Create a new project mcp init my-project # Navigate to project directory cd my-project # Install dependencies npm install ``` -------------------------------- ### Install Node.js Dependencies and Start Dev Server Source: https://docs.mcpcodex.ca/getting-started/first-project Installs project dependencies using npm and then starts the development server for the MCPCodex application. The application will be accessible at http://localhost:3000 upon successful startup. ```bash npm install npm run dev ``` -------------------------------- ### Install MCPCodex CLI Source: https://docs.mcpcodex.ca/getting-started/quickstart Installs the MCPCodex Command Line Interface globally using npm and verifies the installation by checking the CLI version. This is the first step to using MCPCodex for code generation. ```bash # Install MCPCodex CLI globally npm install -g @mcpcodex/cli # Verify installation mcp --version ``` -------------------------------- ### Generate Code and Run with MCPCodex CLI Source: https://docs.mcpcodex.ca/getting-started/quickstart Demonstrates how to use the MCPCodex CLI to generate code based on a natural language prompt, start a development server, and run tests. These commands facilitate the AI-driven development workflow. ```bash # Generate a simple API endpoint mcp generate "Create a REST API endpoint for user authentication with JWT" # Start development server mcp dev # Run tests mcp test ``` -------------------------------- ### Install SyndiCodex CLI using npm Source: https://docs.mcpcodex.ca/cli Instructions for installing the SyndiCodex CLI globally or locally using npm. This is the primary method to get started with the tool. ```bash # Global installation (recommended) npm install -g @mcpcodex/syndicodex # Alternative package name npm install -g syndicodex # Local installation npm install syndicodex ``` -------------------------------- ### Install MCPCodex CLI via NPM Source: https://docs.mcpcodex.ca/getting-started/installation Installs the MCPCodex command-line interface globally using npm. Ensure Node.js and npm are installed and meet the minimum system requirements. ```bash npm install -g @mcpcodex/cli ``` -------------------------------- ### Create a New MCPCodex Project Source: https://docs.mcpcodex.ca/getting-started/first-project Initializes a new project using the MCPCodex CLI. Users can select from predefined templates like chat-bot, code-analyzer, data-processor, web-scraper, and api-gateway. ```bash mcpcodex create my-first-app ``` -------------------------------- ### Verify MCPCodex CLI Installation Source: https://docs.mcpcodex.ca/getting-started/installation Commands to check if the MCPCodex CLI is installed correctly and to verify authentication status. ```bash mcpcodex --version ``` ```bash mcpcodex auth status ``` -------------------------------- ### Install MCPCodex SDKs (JavaScript/Python) Source: https://docs.mcpcodex.ca/getting-started/installation Installs the MCPCodex Software Development Kits for JavaScript/TypeScript and Python. The JS SDK supports Node.js and browser environments, while the Python SDK includes async support. ```bash npm install @mcpcodex/sdk ``` ```bash pip install mcpcodex ``` -------------------------------- ### Run SyndiCodex CLI Commands Source: https://docs.mcpcodex.ca/cli Examples of core SyndiCodex CLI commands for initiating setup, orchestrating workflows, generating code, chatting with agents, and analyzing codebases. ```bash # Interactive setup wizard syndicodex onboarding # Start autonomous development workflow syndicodex orchestrate "build a secure user authentication API" # Generate production-ready code syndicodex generate "JWT authentication middleware with rate limiting" # Interactive chat with AI agents syndicodex chat # Analyze codebase with production readiness assessment syndicodex analyze --production-ready ``` -------------------------------- ### Deploy MCPCodex Application to Cloud Source: https://docs.mcpcodex.ca/getting-started/first-project Deploys the application to the MCPCodex cloud platform for production use. Supports deployment options like Serverless, Container, and Edge, catering to different scaling and performance needs. ```bash mcpcodex deploy --environment production ``` -------------------------------- ### Authenticate with MCPCodex CLI Source: https://docs.mcpcodex.ca/getting-started/first-project Logs into the MCPCodex platform to enable access to AI agents and services. This command opens a browser for the authentication flow and requires a MCPCodex account. ```bash mcpcodex auth login ``` -------------------------------- ### Quick Start: Generate Code with JavaScript/TypeScript SDK Source: https://docs.mcpcodex.ca/api/sdks A quick start example demonstrating how to initialize the MCPCodex client and generate code using the JavaScript/TypeScript SDK. It shows asynchronous code generation with a specified model and language. ```javascript import { MCPCodex } from '@mcpcodex/sdk'; // Initialize the client const mcp = new MCPCodex({ apiKey: process.env.MCPCODEX_API_KEY }); // Generate code const result = await mcp.agents.generate({ prompt: "Create a React component for user authentication", model: "claude-3-sonnet", language: "typescript" }); console.log(result.content); ``` -------------------------------- ### Quick Start: Generate Code with Python SDK Source: https://docs.mcpcodex.ca/api/sdks A quick start example for the MCPCodex Python SDK, showing how to initialize the client and perform an asynchronous code generation request. It utilizes Python's asyncio for non-blocking operations. ```python import mcpcodex import asyncio # Initialize the client client = mcpcodex.Client(api_key="your-api-key") async def generate_code(): result = await client.agents.generate( prompt="Create a FastAPI endpoint for user authentication", model="claude-3-sonnet", language="python" ) print(result.content) # Run the async function asyncio.run(generate_code()) ``` -------------------------------- ### Quick Start: Generate Code with MCPCodex API (cURL) Source: https://docs.mcpcodex.ca/api This snippet demonstrates how to quickly get started with the MCPCodex API by making a POST request to the generate endpoint. It requires an API key for authentication and a JSON payload specifying the prompt, model, and context (framework and language). The output will be generated code based on the prompt. ```shell curl -X POST "https://api.mcpcodex.ca/v2/generate" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "Create a REST API endpoint for user authentication", "model": "claude-3-opus", "context": { "framework": "express", "language": "typescript" } }' ``` -------------------------------- ### Configure MCPCodex Project (JavaScript) Source: https://docs.mcpcodex.ca/getting-started/quickstart Defines the configuration for MCPCodex within a JavaScript file (`mcpcodex.config.js`). It specifies the AI model to use, API key (recommended to be an environment variable), and settings for different AI agents and integrations. ```javascript // mcpcodex.config.js export default { model: 'claude-3-opus', apiKey: process.env.MCP_API_KEY, agents: { coder: { temperature: 0.2 }, reviewer: { temperature: 0.1 }, tester: { temperature: 0.3 } }, integrations: { github: true, vscode: true } }; ``` -------------------------------- ### Troubleshoot 'Command not found' Source: https://docs.mcpcodex.ca/getting-started/installation If the 'mcpcodex' command is not recognized, this command helps find the npm installation prefix, which may need to be added to your system's PATH environment variable. ```bash npm config get prefix ``` -------------------------------- ### Install and Use SyndiCodex CLI Source: https://docs.mcpcodex.ca/api/code-generation Provides commands for installing the SyndiCodex CLI using npm and examples of its usage for quick code generation, advanced autonomous workflows, and interactive chat with AI agents. This CLI offers a streamlined interface to the code generation capabilities. ```bash # Install SyndiCodex CLI npm install -g @mcpcodex/syndicodex # or npm install -g syndicodex # Quick autonomous code generation syndicodex generate "Create a secure JWT authentication middleware" # Advanced autonomous workflow syndicodex orchestrate "build a complete user management API with tests" # Interactive chat with AI agents syndicodex chat ``` -------------------------------- ### Troubleshoot Permission Denied (macOS/Linux) Source: https://docs.mcpcodex.ca/getting-started/installation On macOS or Linux systems, permission errors during global npm installation can often be resolved by using 'sudo' or by configuring npm permissions correctly. ```bash sudo npm install -g @mcpcodex/cli ``` -------------------------------- ### Generate Code Programmatically with MCPCodex SDK (JavaScript) Source: https://docs.mcpcodex.ca/getting-started/quickstart Shows how to use the MCPCodex SDK within a JavaScript application to generate code. It involves initializing the SDK with API credentials and model configuration, then calling the `generate` method with a prompt and contextual information. ```javascript import { MCPCodex } from '@mcpcodex/sdk'; // Initialize the SDK const mcp = new MCPCodex({ apiKey: process.env.MCP_API_KEY, model: 'claude-3-opus' }); // Generate code with context const result = await mcp.generate({ prompt: 'Create a user authentication service', context: { framework: 'express', database: 'postgresql', features: ['jwt', 'refresh-tokens', 'rate-limiting'] } }); console.log('Generated code:', result.code); ``` -------------------------------- ### Pull MCPCodex Docker Image Source: https://docs.mcpcodex.ca/getting-started/installation Pulls the latest MCPCodex CLI Docker image. This is useful for running MCPCodex in an isolated environment without direct system installation. ```bash docker pull mcpcodex/cli:latest ``` -------------------------------- ### Run MCPCodex Docker Container Source: https://docs.mcpcodex.ca/getting-started/installation Runs the MCPCodex CLI within a Docker container. This command executes the latest image and provides an interactive, temporary session. ```bash docker run -it --rm mcpcodex/cli:latest ``` -------------------------------- ### Configure MCPCodex Project Agent Source: https://docs.mcpcodex.ca/getting-started/first-project Defines the AI agent's behavior, model, capabilities, and context settings within the mcp.config.json file. This JSON configuration file is crucial for customizing the AI agent's functionality. ```json { "name": "my-first-app", "version": "1.0.0", "description": "My first MCPCodex application", "agents": { "main": { "type": "chat-assistant", "model": "claude-3-sonnet", "capabilities": ["code-generation", "text-processing"], "context": { "maxTokens": 4000, "temperature": 0.7 } } }, "endpoints": { "chat": "/api/chat", "health": "/api/health" } } ``` -------------------------------- ### SyndiCodex Orchestrate Command Example Source: https://docs.mcpcodex.ca/cli Example of using the `syndicodex orchestrate` command to launch autonomous development workflows, with an option for production readiness. ```bash syndicodex orchestrate "e-commerce platform with payments" --production-ready ``` -------------------------------- ### Enter Interactive Chat Mode with MCPCodex Agent Source: https://docs.mcpcodex.ca/getting-started/first-project Activates an interactive chat session with the AI agent through the MCPCodex CLI. This mode allows for real-time conversation and testing of the agent's interactive capabilities. ```bash mcpcodex chat --interactive ``` -------------------------------- ### SyndiCodex Generate Command Example Source: https://docs.mcpcodex.ca/cli Example of using the `syndicodex generate` command for autonomous code generation, specifying frameworks and test inclusion. ```bash syndicodex generate "React component with tests" --include-tests --framework react ``` -------------------------------- ### Test MCPCodex Agent Chat Endpoint Source: https://docs.mcpcodex.ca/getting-started/first-project Tests the chat functionality of the AI agent by sending a query via the MCPCodex CLI. This allows for quick verification of the agent's response capabilities. ```bash mcpcodex test chat "Hello, can you help me write a function?" ``` -------------------------------- ### SyndiCodex Chat Command Example Source: https://docs.mcpcodex.ca/cli Example of using the `syndicodex chat` command for multi-agent interaction, specifying agents and enabling memory. ```bash syndicodex chat --agents security,performance,architecture --memory ``` -------------------------------- ### SyndiCodex Analyze Command Example Source: https://docs.mcpcodex.ca/cli Example of using the `syndicodex analyze` command for codebase analysis, including security scans, performance audits, and pattern detection. ```bash syndicodex analyze --security-scan --performance-audit --patterns ``` -------------------------------- ### Initialize React Chatbot Project with MCPCodex SDK Source: https://docs.mcpcodex.ca/guides/chat-bot This snippet demonstrates how to initialize a new React project using TypeScript and install the MCPCodex SDK along with other essential dependencies like socket.io-client. It covers the command-line interface commands for project creation and dependency installation. ```bash npx create-react-app my-chatbot --template typescript cd my-chatbot ``` ```bash npm install @mcpcodex/sdk @mcpcodex/react socket.io-client npm install -D @types/socket.io-client ``` -------------------------------- ### Python SDK: Async Streaming Example Source: https://docs.mcpcodex.ca/api/sdks Demonstrates asynchronous streaming of responses using the MCPCodex Python SDK. This example shows how to iterate over a stream of chunks for real-time data processing. ```python async def stream_generation(): async with client.agents.generate_stream( prompt="Create a Django model", model="claude-3-sonnet" ) as stream: async for chunk in stream: print(chunk.content, end="", flush=True) ``` -------------------------------- ### JavaScript/TypeScript SDK: Type Definition Example Source: https://docs.mcpcodex.ca/api/sdks Illustrates the type safety provided by the MCPCodex JavaScript/TypeScript SDK with an example interface for the generate request. This enhances code reliability and developer experience. ```typescript interface GenerateRequest { prompt: string; model: ModelType; language?: string; context?: ProjectContext; } ``` -------------------------------- ### JavaScript/TypeScript Implementation Example Source: https://docs.mcpcodex.ca/api/errors An example demonstrating how to handle API calls and errors using JavaScript/TypeScript, including custom error classes and retry logic. ```APIDOC ## Implementation Examples: JavaScript/TypeScript ```javascript async function handleAPICall(endpoint, options = {}) { try { const response = await fetch(`https://api.mcpcodex.ca${endpoint}`, { headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json', ...options.headers }, ...options }); // Always check the response status if (!response.ok) { const errorData = await response.json(); switch (response.status) { case 400: throw new ValidationError(errorData.error.message, errorData.error.details); case 401: throw new AuthenticationError(errorData.error.message); case 403: throw new AuthorizationError(errorData.error.message); case 404: throw new NotFoundError(errorData.error.message); case 429: const retryAfter = response.headers.get('Retry-After'); throw new RateLimitError(errorData.error.message, retryAfter); case 500: case 502: case 503: throw new ServerError(errorData.error.message, errorData.request_id); default: throw new APIError(errorData.error.message, response.status); } } return await response.json(); } catch (error) { if (error instanceof RateLimitError) { // Implement exponential backoff await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000)); return handleAPICall(endpoint, options); // Retry } if (error instanceof ServerError) { console.error('Server error occurred:', error.requestId); // Log for monitoring/alerting } throw error; } } // Custom error classes (example) class APIError extends Error { constructor(message, status) { super(message); this.name = 'APIError'; this.status = status; } } class RateLimitError extends APIError { constructor(message, retryAfter) { super(message, 429); this.name = 'RateLimitError'; this.retryAfter = parseInt(retryAfter); } } class ServerError extends APIError { constructor(message, requestId) { super(message, 500); this.name = 'ServerError'; this.requestId = requestId; } } // Placeholder for other specific error classes like ValidationError, AuthenticationError, etc. class ValidationError extends APIError {} class AuthenticationError extends APIError {} class AuthorizationError extends APIError {} class NotFoundError extends APIError {} ``` ``` -------------------------------- ### Install JavaScript/TypeScript SDK via npm Source: https://docs.mcpcodex.ca/api/sdks Install the MCPCodex JavaScript/TypeScript SDK using npm. This package provides a client for interacting with MCPCodex APIs, supporting both Node.js and browser environments with TypeScript compatibility. ```bash npm install @mcpcodex/sdk ``` -------------------------------- ### JavaScript/TypeScript SDK: Streaming Support Example Source: https://docs.mcpcodex.ca/api/sdks Demonstrates how to utilize the streaming capabilities of the MCPCodex JavaScript/TypeScript SDK to receive content in chunks. This is useful for real-time responses or large data streams. ```javascript const stream = await mcp.agents.generateStream({ prompt: "Create a REST API", onChunk: (chunk) => { process.stdout.write(chunk.content); } }); ``` -------------------------------- ### Vector-Based Context Retrieval Example (JavaScript) Source: https://docs.mcpcodex.ca/mcp/context Demonstrates retrieving relevant context information based on semantic similarity using a vector store. It takes a query, project identifier, a limit for results, and a similarity threshold as input, returning the most relevant context entries. ```javascript // Context retrieval example const relevantContext = await contextStore.retrieve({ query: "authentication implementation patterns", project: "user-auth-service", limit: 10, threshold: 0.8 }); ``` -------------------------------- ### Install JavaScript/TypeScript SDK via yarn Source: https://docs.mcpcodex.ca/api/sdks Install the MCPCodex JavaScript/TypeScript SDK using yarn. This command adds the SDK package to your project, enabling you to integrate MCPCodex functionalities into your web or Node.js applications. ```bash yarn add @mcpcodex/sdk ``` -------------------------------- ### Install Python SDK via pip Source: https://docs.mcpcodex.ca/api/sdks Install the MCPCodex Python SDK using pip. This package enables Python developers to easily integrate with MCPCodex services, supporting asynchronous operations. ```bash pip install mcpcodex ``` -------------------------------- ### MCP Agent Communication (JavaScript) Source: https://docs.mcpcodex.ca/api/websockets Shows how to connect to an MCP Agent Pool with specific configurations and send a request for code review. This example focuses on agent interaction. ```javascript // Connect to MCP Agent Pool ws.send(JSON.stringify({ type: 'connect_agent', agent_type: 'code_reviewer', config: { language: 'typescript', strictness: 'high', focus_areas: ['security', 'performance'] } })); // Send code for review ws.send(JSON.stringify({ type: 'agent_request', agent_id: 'agent_789', request: { action: 'review_code', payload: { files: [ { path: 'src/auth.ts', content: 'export const validateToken = ...' } ] } } })); ``` -------------------------------- ### Generate Code via cURL and Python Request Source: https://docs.mcpcodex.ca/api/code-generation Demonstrates how to interact with the MCPCodex Code Generation API using cURL for command-line requests and Python's `requests` library for programmatic integration. These examples show how to specify the prompt, desired language, and AI model. ```bash # cURL Example curl -X POST "https://api.mcpcodex.ca/v2/generate" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "prompt": "Create a Python function to parse CSV files", "language": "python", "model": "claude-3.5-sonnet" }' ``` ```python import requests response = requests.post('https://api.mcpcodex.ca/v2/generate', json={ 'prompt': 'Create a React component for a todo list', 'language': 'typescript', 'model': 'gpt-4' }, headers={ 'Authorization': 'Bearer YOUR_API_KEY' }) print(response.json()) ``` -------------------------------- ### Example Bad Request Error Response Source: https://docs.mcpcodex.ca/api/errors This example demonstrates a 'Bad Request' error response (HTTP 400) due to invalid input data. The 'details' field provides specific information about which fields failed validation and why. ```json { "error": { "code": "validation_error", "message": "Request validation failed", "details": { "name": "Name is required and cannot be empty", "type": "Invalid agent type. Allowed values: chat, code, analysis" } }, "request_id": "req_123456789" } ``` -------------------------------- ### Rate Limit Response Headers Example Source: https://docs.mcpcodex.ca/api/rate-limits This snippet shows the HTTP headers returned by the MCPCodex API to indicate rate limit status. It includes limits, remaining counts, and reset times for hourly, burst, and quota limits. ```http HTTP/1.1 200 OK X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 987 X-RateLimit-Reset: 1647875400 X-RateLimit-Burst-Limit: 50 X-RateLimit-Burst-Remaining: 45 X-RateLimit-Burst-Reset: 1647872460 X-RateLimit-Quota-Limit: 100000 X-RateLimit-Quota-Remaining: 95432 X-RateLimit-Quota-Reset: 1650467400 ``` -------------------------------- ### Example: Bad Request (400) Source: https://docs.mcpcodex.ca/api/errors Illustrates a typical 'Bad Request' error response, often due to validation failures. ```APIDOC ## Bad Request (400) The request was invalid or missing required parameters. ### Common Causes * Missing required fields in request body * Invalid JSON format * Invalid parameter values * Malformed request headers ### Example #### Request ``` POST /api/v1/agents { "name": "", "type": "invalid_type" } ``` #### Response ```json { "error": { "code": "validation_error", "message": "Request validation failed", "details": { "name": "Name is required and cannot be empty", "type": "Invalid agent type. Allowed values: chat, code, analysis" } }, "request_id": "req_123456789" } ``` ``` -------------------------------- ### JavaScript WebSocket Client for Real-time Streaming Source: https://docs.mcpcodex.ca/mcp/streaming Implements a WebSocket client to connect to a server and handle real-time data streams. It includes methods for setting up event handlers, starting code generation via 'tools/call' RPC, and managing stream chunks. Dependencies include the WebSocket API. Outputs are enqueued data chunks or stream end signals. ```javascript class MCPStreamingClient { constructor(url) { this.ws = new WebSocket(url); this.streams = new Map(); this.setupEventHandlers(); } setupEventHandlers() { this.ws.onmessage = (event) => { const message = JSON.parse(event.data); if (message.method === 'stream/chunk') { this.handleStreamChunk(message.params); } else if (message.method === 'stream/end') { this.handleStreamEnd(message.params); } }; } async startCodeGeneration(prompt) { const streamId = this.generateStreamId(); const request = { jsonrpc: "2.0", id: streamId, method: "tools/call", params: { name: "code_generator", arguments: { prompt, stream: true } } }; this.ws.send(JSON.stringify(request)); return new ReadableStream({ start: (controller) => { this.streams.set(streamId, controller); } }); } handleStreamChunk(params) { const { stream_id, data } = params; const controller = this.streams.get(stream_id); if (controller) { controller.enqueue(data); } } } ``` -------------------------------- ### Start Workflow - A2A Communication Hub Source: https://docs.mcpcodex.ca/api/endpoints Initiates a multi-agent collaborative workflow by specifying the workflow ID, participating agents, and context. Returns the workflow session ID and its initial status. This endpoint is part of the A2A Communication Hub. ```json { "workflowId": "string", "agents": "string[]", "context": "object" } ``` ```json { "workflowSessionId": "string", "status": "string" } ``` -------------------------------- ### Handling 429 Too Many Requests Response Source: https://docs.mcpcodex.ca/api/rate-limits This example demonstrates the response received when an API rate limit is exceeded. It includes a 429 status code, a Retry-After header, and a JSON body with details about the exceeded limit and when to retry. ```http HTTP/1.1 429 Too Many Requests Retry-After: 3600 X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1647875400 ``` ```json { "error": { "code": "rate_limit_exceeded", "message": "Rate limit exceeded. Try again in 3600 seconds.", "details": { "limit": 1000, "remaining": 0, "reset_time": 1647875400 } } } ``` -------------------------------- ### Initialize MCP Client in JavaScript Source: https://docs.mcpcodex.ca/mcp/architecture This code snippet demonstrates how to initialize an MCP client in JavaScript. It shows the configuration for connecting to different types of MCP servers, such as Git and filesystem servers, specifying their respective commands or URLs. Dependencies include the MCPClient library. ```javascript const client = new MCPClient({ servers: { git: { command: "git-mcp-server" }, filesystem: { url: "ws://localhost:8080" } } }); ``` -------------------------------- ### Connect to MCPCodex Agent (JavaScript) Source: https://docs.mcpcodex.ca/mcp/agents Demonstrates how to establish a connection to a specific MCPCodex agent, such as a code reviewer, using the JavaScript SDK. Configuration options allow specifying agent type, language, strictness, and focus areas. ```javascript const agent = await mcp.connect({ type: 'code_reviewer', config: { language: 'typescript', strictness: 'high', focus_areas: ['security', 'performance'] } }); console.log('Connected to agent:', agent.id); ``` -------------------------------- ### Generate a REST API using MCPCodex CLI Source: https://docs.mcpcodex.ca/index Demonstrates how to use the MCPCodex CLI to generate a user management API with authentication, CRUD operations, and rate limiting. It specifies the use of Express and PostgreSQL as technologies. ```Shell mcp generate "Create a user management API with authentication, CRUD operations, and rate limiting using Express and PostgreSQL" ``` -------------------------------- ### Get Workflow Status - A2A Communication Hub Source: https://docs.mcpcodex.ca/api/endpoints Retrieves the status of a specific multi-agent workflow, including its current stage and the status of individual agents involved. This endpoint is part of the A2A Communication Hub. ```json { "status": "string", "currentStage": "string", "agents": [ { "agentId": "string", "status": "string" } ] } ``` -------------------------------- ### Authentication Service API Source: https://docs.mcpcodex.ca/api/endpoints Endpoints for user registration and login. ```APIDOC ## POST /auth/register ### Description Register a new user account. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **username** (string) - Required - The desired username. - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "string", "email": "string", "password": "string" } ``` ### Response #### Success Response (200) - **userId** (string) - The unique identifier for the newly created user. - **token** (string) - An authentication token for the new user. #### Response Example ```json { "userId": "string", "token": "string" } ``` --- ## POST /auth/login ### Description Authenticate user and generate JWT tokens. ### Method POST ### Endpoint /auth/login ### Parameters #### Request Body - **username** (string) - Required - The user's username. - **password** (string) - Required - The user's password. ### Request Example ```json { "username": "string", "password": "string" } ``` ### Response #### Success Response (200) - **accessToken** (string) - The JWT access token for authenticated requests. - **refreshToken** (string) - The JWT refresh token for obtaining new access tokens. #### Response Example ```json { "accessToken": "string", "refreshToken": "string" } ``` ``` -------------------------------- ### Code Snippet: Project Structure Analysis (JavaScript) Source: https://docs.mcpcodex.ca/mcp This snippet demonstrates how MCP can automatically understand a project's structure by analyzing directory and file organization. It helps in identifying components, services, and utility functions, forming a foundational part of the project's context. ```javascript // MCP automatically understands your project structure ├── src/ │ ├── components/ # React components │ ├── services/ # API integration │ └── utils/ # Helper functions └── docs/ # Project documentation ``` -------------------------------- ### POST /v2/generate Source: https://docs.mcpcodex.ca/api/code-generation Generates code based on a provided prompt and specified parameters. Supports various languages, AI models, and customization options. ```APIDOC ## POST /v2/generate ### Description This endpoint generates code based on a user-provided prompt. You can specify the desired programming language, AI model, and various generation parameters to tailor the output. ### Method POST ### Endpoint /v2/generate ### Parameters #### Request Body - **prompt** (string) - Required - The natural language prompt describing the code to be generated. - **language** (string) - Optional - The programming language for the generated code. Defaults to 'python'. Supported values: 'python', 'typescript', 'javascript', 'rust', 'go', 'java'. - **model** (string) - Optional - The specific AI model to use for generation. Defaults to auto-selection. Supported values: 'claude-3.5-sonnet', 'gpt-4', 'gpt-3.5-turbo', 'gemini'. - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **temperature** (float) - Optional - Controls the randomness of the generation. Range: 0.0-1.0. Defaults to 0.7. - **include_explanation** (boolean) - Optional - Whether to include an explanation of the generated code. Defaults to true. - **include_tests** (boolean) - Optional - Whether to generate unit tests for the code. Defaults to false. - **style_preferences** (object) - Optional - An object to specify style and framework preferences. - **framework** (string) - Optional - Preferred framework (e.g., 'react'). - **coding_style** (string) - Optional - Preferred coding style (e.g., 'functional'). - **error_handling** (string) - Optional - Preferred error handling strategy (e.g., 'comprehensive'). ### Request Example ```json { "prompt": "Create a Python function to parse CSV files", "language": "python", "model": "claude-3.5-sonnet", "include_tests": true, "style_preferences": { "error_handling": "comprehensive" } } ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the generation request. - **code** (string) - The generated source code. - **explanation** (string) - An explanation of the generated code (if requested). - **tests** (string) - Generated unit tests (if requested). - **model_used** (string) - The AI model that performed the generation. - **language** (string) - The programming language of the generated code. - **confidence_score** (float) - The AI's confidence in the generated code. - **estimated_tokens** (integer) - The estimated number of tokens used for the generation. - **generation_time_ms** (integer) - The time taken for code generation in milliseconds. - **warnings** (array of strings) - Any warnings or suggestions related to the generation. #### Response Example ```json { "id": "gen_abc123", "code": "def parse_csv(file_path):\n import csv\n data = []\n try:\n with open(file_path, 'r', newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n data.append(row)\n return data\n except FileNotFoundError:\n print(f'Error: File not found at {file_path}')\n return None\n except Exception as e:\n print(f'An error occurred: {e}')\n return None", "explanation": "This Python function `parse_csv` takes a file path as input, reads a CSV file using the `csv` module, and returns the data as a list of lists. It includes basic error handling for `FileNotFoundError` and other potential exceptions.", "tests": "import unittest\nfrom your_module import parse_csv # Assuming the function is in your_module.py\n\nclass TestParseCsv(unittest.TestCase):\n\n def test_parse_csv_valid(self):\n # Create a dummy CSV file for testing\n with open('test.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(['header1', 'header2'])\n writer.writerow(['value1', 'value2'])\n\n result = parse_csv('test.csv')\n self.assertEqual(result, [['header1', 'header2'], ['value1', 'value2']])\n # Clean up the dummy file\n import os\n os.remove('test.csv')\n\n def test_parse_csv_file_not_found(self):\n result = parse_csv('non_existent_file.csv')\n self.assertIsNone(result)\n\nif __name__ == '__main__':\n unittest.main()", "model_used": "claude-3.5-sonnet", "language": "python", "confidence_score": 0.92, "estimated_tokens": 350, "generation_time_ms": 1200, "warnings": [] } ``` ### Error Handling - **400**: Invalid request parameters (e.g., missing required fields, invalid enum values). - **401**: Authentication failed (e.g., invalid API key). - **429**: Rate limit exceeded. Please upgrade your plan or wait for the limit to reset. - **500**: Internal server error. Please try again later or contact support. ``` -------------------------------- ### Multi-Agent Collaboration Workflow (JavaScript) Source: https://docs.mcpcodex.ca/mcp/agents Illustrates a multi-agent workflow where a coder agent generates code, a reviewer agent analyzes it, and a tester agent creates tests. This demonstrates chaining agent capabilities for a complete feature development process. ```javascript // Multi-agent collaboration const coder = await mcp.connect({ type: 'coder' }); const reviewer = await mcp.connect({ type: 'reviewer' }); const tester = await mcp.connect({ type: 'tester' }); // Generate code const code = await coder.generate({ prompt: 'Create user authentication endpoint', framework: 'express' }); // Review the generated code const review = await reviewer.analyze(code); // Generate tests based on the code const tests = await tester.createTests({ code: code.result, coverage_target: 90 }); ``` -------------------------------- ### Connect to WebSocket API (JavaScript) Source: https://docs.mcpcodex.ca/api/websockets Establishes a WebSocket connection to the MCPCodex API and handles authentication using an API key. It also sets up listeners for incoming messages and errors. ```javascript const ws = new WebSocket('wss://api.mcpcodex.ca/v2/ws'); ws.onopen = () => { // Authenticate with your API key ws.send(JSON.stringify({ type: 'auth', token: 'mcp_sk_live_1234567890abcdef' })); }; ws.onmessage = (event) => { const message = JSON.parse(event.data); console.log('Received:', message); }; ws.onerror = (error) => { console.error('WebSocket error:', error); }; ``` -------------------------------- ### Send Code Review Request to Agent (JavaScript) Source: https://docs.mcpcodex.ca/mcp/agents Shows how to send a code review request to a connected agent. The request includes the file path, content to be reviewed, and project context such as project type and security level. ```javascript // Send a code review request const review = await agent.request({ action: 'review_code', payload: { files: [ { path: 'src/auth.ts', content: "\nexport const validateToken = (token: string) => {\n // Validate JWT token\n return jwt.verify(token, process.env.SECRET); }; " } ], context: { project_type: 'web_api', security_level: 'high' } } }); console.log('Review results:', review); ``` -------------------------------- ### User Authentication API Source: https://docs.mcpcodex.ca/api/authentication Authenticates a user using email and password and returns JWT tokens. ```APIDOC ## POST /v1/auth/login ### Description Authenticates a user by email and password and returns JWT access and refresh tokens. ### Method POST ### Endpoint /v1/auth/login ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```json { "email": "user@company.com", "password": "secure_password" } ``` ### Response #### Success Response (200) - **access_token** (string) - The JWT access token. - **refresh_token** (string) - The JWT refresh token. - **expires_in** (integer) - The expiration time of the access token in seconds. - **token_type** (string) - The type of token, typically 'Bearer'. #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "refresh_token": "...", "expires_in": 3600, "token_type": "Bearer" } ``` ``` -------------------------------- ### Error Handling Best Practices Source: https://docs.mcpcodex.ca/api/errors Recommended strategies for handling API errors on the client-side and debugging. ```APIDOC ## Error Handling Best Practices ### Client-Side Handling * Always check HTTP status codes before parsing response. * Implement exponential backoff for 5xx errors. * Log `request_id` for debugging and support. * Handle rate limits gracefully with proper delays. ### Debugging Tips * Include `request_id` when contacting support. * Check the API status page for ongoing issues. * Validate request format against API documentation. * Monitor rate limit headers to prevent 429 errors. ``` -------------------------------- ### Register New User - Authentication Service Source: https://docs.mcpcodex.ca/api/endpoints Registers a new user account by accepting username, email, and password. Returns the generated userId and an authentication token. This endpoint is part of the Authentication Service. ```json { "username": "string", "email": "string", "password": "string" } ``` ```json { "userId": "string", "token": "string" } ``` -------------------------------- ### POST /v2/generate Source: https://docs.mcpcodex.ca/api Endpoint for generating code or API specifications using AI models. Requires authentication and a JSON payload specifying the prompt, model, and context. ```APIDOC ## POST /v2/generate ### Description This endpoint allows users to leverage AI models to generate code, API specifications, or other development-related content based on a provided prompt and context. ### Method POST ### Endpoint `/v2/generate` ### Parameters #### Query Parameters None #### Request Body - **prompt** (string) - Required - The natural language prompt describing the desired output. - **model** (string) - Required - The AI model to use for generation (e.g., "claude-3-opus"). - **context** (object) - Optional - Specifies the development context. - **framework** (string) - Optional - The target framework (e.g., "express"). - **language** (string) - Optional - The target programming language (e.g., "typescript"). ### Request Example ```json { "prompt": "Create a REST API endpoint for user authentication", "model": "claude-3-opus", "context": { "framework": "express", "language": "typescript" } } ``` ### Response #### Success Response (200) - **generated_content** (string) - The AI-generated output. #### Response Example ```json { "generated_content": "// Express.js endpoint for user authentication..." } ``` ``` -------------------------------- ### v2.0.0 API Redesign Source: https://docs.mcpcodex.ca/api/changelog Details the major features and breaking changes of version 2.0.0, including a complete API redesign, the introduction of the Model Context Protocol (MCP), multi-agent collaboration, WebSocket support, and enhanced authentication. ```APIDOC ## User Authentication (OAuth 2.0 / JWT) ### Description Enhanced authentication using OAuth 2.0 and JWT for secure API access. ### Method POST ### Endpoint /oauth/token ### Parameters #### Request Body - **grant_type** (string) - Required - 'client_credentials' or 'password'. - **client_id** (string) - Required - Your application's client ID. - **client_secret** (string) - Required - Your application's client secret. - **username** (string) - Optional - User's username (for 'password' grant_type). - **password** (string) - Optional - User's password (for 'password' grant_type). ### Request Example ```json { "grant_type": "client_credentials", "client_id": "your_client_id", "client_secret": "your_client_secret" } ``` ### Response #### Success Response (200) - **access_token** (string) - The JWT access token. - **token_type** (string) - The type of token (e.g., 'Bearer'). - **expires_in** (integer) - The token's expiration time in seconds. #### Response Example ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600 } ``` ``` ```APIDOC ## Multi-Agent Collaboration ### Description Enables systems where multiple agents can collaborate on tasks. ### Method POST ### Endpoint /api/v2/agents/collaborate ### Parameters #### Request Body - **task** (string) - Required - The overall task to be accomplished. - **agents** (array) - Required - A list of agents participating in the collaboration. ### Request Example ```json { "task": "Write a blog post about AI advancements.", "agents": [{"id": "agent-writer", "role": "writer"}, {"id": "agent-editor", "role": "editor"}] } ``` ### Response #### Success Response (200) - **result** (string) - The final output of the collaborative effort. #### Response Example ```json { "result": "The latest advancements in AI are... } ``` ```