|
| 1 | +# Consumindo APIBrasil MCP com Go (Golang) |
| 2 | + |
| 3 | +Exemplo básico usando `net/http`. |
| 4 | + |
| 5 | +## 1. Código (main.go) |
| 6 | + |
| 7 | +```go |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "bufio" |
| 12 | + "bytes" |
| 13 | + "encoding/json" |
| 14 | + "fmt" |
| 15 | + "net/http" |
| 16 | + "strings" |
| 17 | +) |
| 18 | + |
| 19 | +const baseURL = "https://mcp.apibrasil.cloud/mcp" |
| 20 | + |
| 21 | +func main() { |
| 22 | + fmt.Println("Conectando ao fluxo SSE...") |
| 23 | + |
| 24 | + // 1. Iniciar SSE para pegar SessionID |
| 25 | + resp, err := http.Get(baseURL) |
| 26 | + if err != nil { |
| 27 | + panic(err) |
| 28 | + } |
| 29 | + defer resp.Body.Close() |
| 30 | + |
| 31 | + scanner := bufio.NewScanner(resp.Body) |
| 32 | + var postURL string |
| 33 | + |
| 34 | + // Loop simples para ler o evento 'endpoint' |
| 35 | + // Em produção, use uma lib SSE completa |
| 36 | + for scanner.Scan() { |
| 37 | + line := scanner.Text() |
| 38 | + fmt.Println("Recebido:", line) |
| 39 | + |
| 40 | + if strings.HasPrefix(line, "data: ") { |
| 41 | + // O servidor manda o endpoint relativo no campo data |
| 42 | + endpoint := strings.TrimPrefix(line, "data: ") |
| 43 | + // Ajuste para montar URL completa |
| 44 | + if strings.HasPrefix(endpoint, "/") { |
| 45 | + // ex: /mcp?sessionId=xyz |
| 46 | + postURL = "https://mcp.apibrasil.cloud" + endpoint |
| 47 | + } else { |
| 48 | + postURL = endpoint |
| 49 | + } |
| 50 | + fmt.Println("Endpoint de POST detectado:", postURL) |
| 51 | + break // Temos o que precisamos para fazer chamadas |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + if postURL == "" { |
| 56 | + fmt.Println("Não foi possível obter SessionID.") |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + // 2. Fazer uma chamada de ferramenta (JSON-RPC) |
| 61 | + payload := map[string]interface{}{ |
| 62 | + "jsonrpc": "2.0", |
| 63 | + "method": "tools/call", |
| 64 | + "id": 1, |
| 65 | + "params": map[string]interface{}{ |
| 66 | + "name": "cep_lookup", |
| 67 | + "arguments": map[string]interface{}{ |
| 68 | + "cep": "01001000", |
| 69 | + "bearer": "SEU_BEARER", |
| 70 | + "deviceToken": "SEU_DEVICE_TOKEN", |
| 71 | + }, |
| 72 | + }, |
| 73 | + } |
| 74 | + |
| 75 | + jsonData, _ := json.Marshal(payload) |
| 76 | + postResp, err := http.Post(postURL, "application/json", bytes.NewBuffer(jsonData)) |
| 77 | + if err != nil { |
| 78 | + panic(err) |
| 79 | + } |
| 80 | + defer postResp.Body.Close() |
| 81 | + |
| 82 | + fmt.Println("Chamada enviada. Status:", postResp.Status) |
| 83 | + // Ler resposta... |
| 84 | +} |
| 85 | +``` |
0 commit comments