{
  "openapi": "3.1.0",
  "info": {
    "title": "Leque de Números - Contabilidade e Gestão Fiscal API & MCP Server",
    "version": "1.0.0",
    "description": "API RESTful oficial e endpoint MCP (Model Context Protocol 2024-11-05) ativo da Leque de Números - Gabinete de Contabilidade em Matosinhos e Porto. Fornece ferramentas de cálculo e simulação fiscal portuguesa (IRS, IRC, IVA, Segurança Social), processamento salarial, validação oficial de NIF e consultoria contabilística.",
    "contact": {
      "name": "Leque de Números, Lda.",
      "url": "https://www.lequedenumeros.pt/contacto",
      "email": "geral@lequedenumeros.pt"
    },
    "license": {
      "name": "Proprietary",
      "url": "https://www.lequedenumeros.pt/politica-privacidade"
    }
  },
  "servers": [
    {
      "url": "https://www.lequedenumeros.pt",
      "description": "Servidor de Produção Oficial"
    },
    {
      "url": "http://localhost:3000",
      "description": "Servidor de Testes / Desenvolvimento Local"
    }
  ],
  "x-mcp-server": {
    "protocolVersion": "2024-11-05",
    "endpoint": "/mcp",
    "sseEndpoint": "/mcp/sse",
    "status": "active",
    "capabilities": {
      "tools": { "listChanged": true },
      "resources": { "subscribe": false, "listChanged": false },
      "prompts": { "listChanged": false },
      "logging": {}
    },
    "serverInfo": {
      "name": "lequedenumeros-mcp-server",
      "version": "1.0.0"
    }
  },
  "paths": {
    "/mcp": {
      "get": {
        "summary": "MCP Server Discovery & OpenAPI Specification",
        "description": "Retorna o estado ativo do servidor MCP, capacidades e o documento OpenAPI 3.1 completo.",
        "operationId": "getMcpDiscovery",
        "responses": {
          "200": {
            "description": "Servidor MCP ativo e documento OpenAPI",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/McpDiscoveryResponse"
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "MCP JSON-RPC 2.0 Handler",
        "description": "Ponto de entrada oficial do protocolo MCP. Suporta os métodos 'initialize', 'notifications/initialized', 'ping', 'tools/list', 'tools/call', 'resources/list', e 'prompts/list'.",
        "operationId": "handleMcpJsonRpc",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/JsonRpcRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resposta JSON-RPC 2.0 do servidor MCP",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/JsonRpcResponse"
                }
              }
            }
          }
        }
      }
    },
    "/mcp/sse": {
      "get": {
        "summary": "MCP Server-Sent Events (SSE) Stream",
        "description": "Canal de transporte SSE padrão do Model Context Protocol para agentes e clientes MCP persistentes.",
        "operationId": "getMcpSseStream",
        "responses": {
          "200": {
            "description": "Fluxo de eventos SSE ativo",
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/openapi.json": {
      "get": {
        "summary": "Documento OpenAPI 3.1 em Formato JSON",
        "description": "Especificação integral de todos os endpoints e esquemas de dados da plataforma Leque Contabilidade.",
        "operationId": "getOpenApiJson",
        "responses": {
          "200": {
            "description": "Documento OpenAPI 3.1",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/openapi.yaml": {
      "get": {
        "summary": "Documento OpenAPI 3.1 em Formato YAML",
        "description": "Especificação OpenAPI 3.1 formatada em YAML para clientes e geradores de código.",
        "operationId": "getOpenApiYaml",
        "responses": {
          "200": {
            "description": "Documento OpenAPI 3.1 YAML",
            "content": {
              "application/x-yaml": {
                "schema": {
                  "type": "string"
                }
              }
            }
          }
        }
      }
    },
    "/.well-known/mcp.json": {
      "get": {
        "summary": "Manifesto de Descoberta MCP",
        "description": "Manifesto de configuração e descoberta para clientes MCP (Anthropic / Claude / Linux Foundation).",
        "operationId": "getMcpManifest",
        "responses": {
          "200": {
            "description": "Manifesto MCP oficial",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/.well-known/ai-plugin.json": {
      "get": {
        "summary": "Manifesto AI Plugin",
        "description": "Manifesto padrão para conexão de agentes e modelos de linguagem à API e ao servidor MCP da Leque Contabilidade.",
        "operationId": "getAiPluginManifest",
        "responses": {
          "200": {
            "description": "Manifesto AI Plugin",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    },
    "/api/chat": {
      "post": {
        "summary": "Assistente de Fiscalidade e Contabilidade",
        "description": "Processa perguntas técnicas sobre IRC, IRS, IVA, regimes tributários e constituição de empresas em Portugal.",
        "operationId": "askFiscalAssistant",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/ChatRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resposta do assistente especializado",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/ChatResponse"
                }
              }
            }
          }
        }
      }
    },
    "/api/artigos": {
      "get": {
        "summary": "Pesquisa de Guias e Artigos Fiscais",
        "description": "Obtém artigos práticos sobre contabilidade, frotas TVDE, alojamento local e novidades fiscais 2026.",
        "operationId": "listArticles",
        "parameters": [
          {
            "name": "q",
            "in": "query",
            "description": "Termo de pesquisa livre",
            "required": false,
            "schema": { "type": "string" }
          },
          {
            "name": "categoria",
            "in": "query",
            "description": "Filtro por categoria",
            "required": false,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "Lista de artigos encontrados",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "total": { "type": "integer" },
                    "articles": { "type": "array", "items": { "type": "object" } }
                  }
                }
              }
            }
          }
        }
      }
    },
    "/api/simuladores/validar-nif": {
      "get": {
        "summary": "Validação Oficial de NIF/NIPC Português",
        "description": "Verifica se um NIF ou NIPC de 9 dígitos é válido segundo o algoritmo oficial de Módulo 11 da Autoridade Tributária.",
        "operationId": "validateNifGet",
        "parameters": [
          {
            "name": "nif",
            "in": "query",
            "description": "NIF com 9 dígitos numéricos",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "Resultado da validação do NIF",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NifValidationResult"
                }
              }
            }
          }
        }
      },
      "post": {
        "summary": "Validação de NIF (POST)",
        "description": "Valida NIF via corpo da mensagem.",
        "operationId": "validateNifPost",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": ["nif"],
                "properties": {
                  "nif": { "type": "string" }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resultado da validação do NIF",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/NifValidationResult"
                }
              }
            }
          }
        }
      }
    },
    "/api/simuladores/salario-liquido": {
      "post": {
        "summary": "Simulador de Salário Líquido e Encargos da Empresa",
        "description": "Calcula desconto de IRS, TSU do colaborador (11%), TSU da entidade patronal (23,75%) e subsídio de refeição.",
        "operationId": "simulateSalary",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/SalarySimulationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Detalhamento salarial e fiscal",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/SalarySimulationResult"
                }
              }
            }
          }
        }
      }
    },
    "/api/simuladores/iva": {
      "post": {
        "summary": "Simulador e Cálculo de IVA",
        "description": "Calcula valor base líquido, montante de IVA e valor bruto pelas taxas vigentes (23%, 13%, 6%, 0%).",
        "operationId": "simulateVat",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/VatSimulationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Cálculo detalhado do IVA",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/VatSimulationResult"
                }
              }
            }
          }
        }
      }
    },
    "/api/simuladores/recibos-verdes": {
      "post": {
        "summary": "Simulador de Recibos Verdes / Trabalhadores Independentes",
        "description": "Simula tributação em sede de IRS e Segurança Social para trabalhadores a recibos verdes.",
        "operationId": "simulateFreelancer",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/FreelancerSimulationRequest"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Resultado da simulação de recibos verdes",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/FreelancerSimulationResult"
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "McpDiscoveryResponse": {
        "type": "object",
        "properties": {
          "openapi": { "type": "string", "example": "3.1.0" },
          "info": { "type": "object" },
          "mcp": {
            "type": "object",
            "properties": {
              "status": { "type": "string", "example": "active" },
              "protocolVersion": { "type": "string", "example": "2024-11-05" },
              "serverInfo": { "type": "object" },
              "capabilities": { "type": "object" }
            }
          },
          "tools": { "type": "array", "items": { "type": "object" } }
        }
      },
      "JsonRpcRequest": {
        "type": "object",
        "required": ["jsonrpc", "method"],
        "properties": {
          "jsonrpc": { "type": "string", "enum": ["2.0"] },
          "id": { "type": ["string", "number", "null"] },
          "method": { "type": "string", "example": "tools/list" },
          "params": { "type": "object" }
        }
      },
      "JsonRpcResponse": {
        "type": "object",
        "required": ["jsonrpc"],
        "properties": {
          "jsonrpc": { "type": "string", "enum": ["2.0"] },
          "id": { "type": ["string", "number", "null"] },
          "result": { "type": "object" },
          "error": {
            "type": "object",
            "properties": {
              "code": { "type": "integer" },
              "message": { "type": "string" },
              "data": { "type": "object" }
            }
          }
        }
      },
      "ChatRequest": {
        "type": "object",
        "required": ["message"],
        "properties": {
          "message": { "type": "string", "example": "Como abrir atividade nas finanças como trabalhador independente?" },
          "history": {
            "type": "array",
            "items": {
              "type": "object",
              "properties": {
                "role": { "type": "string", "enum": ["user", "model"] },
                "text": { "type": "string" }
              }
            }
          }
        }
      },
      "ChatResponse": {
        "type": "object",
        "properties": {
          "reply": { "type": "string" },
          "source": { "type": "string" }
        }
      },
      "NifValidationResult": {
        "type": "object",
        "properties": {
          "isValid": { "type": "boolean" },
          "nif": { "type": "string" },
          "entityType": { "type": "string" },
          "message": { "type": "string" }
        }
      },
      "SalarySimulationRequest": {
        "type": "object",
        "required": ["grossMonthlySalary"],
        "properties": {
          "grossMonthlySalary": { "type": "number", "example": 1500 },
          "maritalStatus": { "type": "string", "enum": ["solteiro", "casado_1_titular", "casado_2_titulares"], "default": "solteiro" },
          "dependents": { "type": "integer", "default": 0 },
          "mealAllowancePerDay": { "type": "number", "default": 6.00 },
          "mealAllowanceType": { "type": "string", "enum": ["numerario", "cartao"], "default": "cartao" },
          "daysWorked": { "type": "integer", "default": 22 }
        }
      },
      "SalarySimulationResult": {
        "type": "object",
        "properties": {
          "grossBase": { "type": "number" },
          "socialSecurityEmployee": { "type": "number" },
          "irsRetention": { "type": "number" },
          "mealAllowanceTotal": { "type": "number" },
          "netSalary": { "type": "number" },
          "socialSecurityEmployer": { "type": "number" },
          "totalCostForCompany": { "type": "number" }
        }
      },
      "VatSimulationRequest": {
        "type": "object",
        "required": ["amount"],
        "properties": {
          "amount": { "type": "number", "example": 1000 },
          "vatRate": { "type": "number", "enum": [23, 13, 6, 0], "default": 23 },
          "isGross": { "type": "boolean", "default": false }
        }
      },
      "VatSimulationResult": {
        "type": "object",
        "properties": {
          "netAmount": { "type": "number" },
          "vatRate": { "type": "number" },
          "vatAmount": { "type": "number" },
          "grossTotal": { "type": "number" }
        }
      },
      "FreelancerSimulationRequest": {
        "type": "object",
        "required": ["annualRevenue"],
        "properties": {
          "annualRevenue": { "type": "number", "example": 30000 },
          "activityType": { "type": "string", "enum": ["servicos_151", "outros_servicos", "vendas"], "default": "servicos_151" },
          "firstYearActivity": { "type": "boolean", "default": false }
        }
      },
      "FreelancerSimulationResult": {
        "type": "object",
        "properties": {
          "annualRevenue": { "type": "number" },
          "taxableBaseIRS": { "type": "number" },
          "estimatedIRS": { "type": "number" },
          "socialSecurityAnnual": { "type": "number" },
          "estimatedNetIncome": { "type": "number" },
          "monthlyAverageNet": { "type": "number" }
        }
      }
    }
  }
}
