Discover Awesome MCP Servers
Extend your agent with 54,476 capabilities via MCP servers.
- All54,476
- Developer Tools3,867
- Search1,714
- Research & Data1,557
- AI Integration Systems229
- Cloud Platforms219
- Data & App Analysis181
- Database Interaction177
- Remote Shell Execution165
- Browser Automation147
- Databases145
- Communication137
- AI Content Generation127
- OS Automation120
- Programming Docs Access109
- Content Fetching108
- Note Taking97
- File Systems96
- Version Control93
- Finance91
- Knowledge & Memory90
- Monitoring79
- Security71
- Image & Video Processing69
- Digital Note Management66
- AI Memory Systems62
- Advanced AI Reasoning59
- Git Management Tools58
- Cloud Storage51
- Entertainment & Media43
- Virtualization42
- Location Services35
- Web Automation & Stealth32
- Media Content Processing32
- Calendar Management26
- Ecommerce & Retail18
- Speech Processing18
- Customer Data Platforms16
- Travel & Transportation14
- Education & Learning Tools13
- Home Automation & IoT13
- Web Search Integration12
- Health & Wellness10
- Customer Support10
- Marketing9
- Games & Gamification8
- Google Cloud Integrations7
- Art & Culture4
- Language Translation3
- Legal & Compliance2
Athena MCP
An MCP server that provides a reasoning sidekick for tool-using agents with a single 'think' tool for tackling complex problems. It allows agents to consult powerful reasoning models like Claude Opus or GPT-5 only when needed, keeping costs low while maintaining control over side effects.
agentbill-mcp
MCP server for AI agent billing. Preflight spend checks before agent runs. Post-execution usage billing via two MCP tools: preflight() and record_event().
mcp-ebay
Enables AI agents to search products, view item details, track and place bids, make Buy It Now purchases, view order history, and track shipments on eBay via browser automation with Playwright.
node-opcua-modeler-mcp-server
Provides AI agents with offline access to OPC UA companion specification types, dependencies, and engineering units for industrial modeling.
vertex-cli
Enables lookup of Nostr profiles and checking of Vertex API credit balance using the Vertex API.
Google Drive MCP Server
Enables interaction with Google Drive files and Google Sheets through search, read, and write operations. Supports automatic conversion of Google Workspace files to readable formats and direct spreadsheet cell updates.
神岛地图数据统计
Fornece acesso a dados de usuários, informações de mapas e estatísticas da plataforma Shenzhou.
Company Records
Exposes a fictional B2B CRM database (companies, contacts, deals) as callable MCP tools, enabling AI agents to answer natural-language questions about company records, contacts, and pipeline data.
nstbrowser-playwright-mcp
Combines NSTBrowser profile management with Playwright browser automation via CDP, enabling browser automation through NSTBrowser profiles.
nanobanana-mcp
MCP server for AI image generation supporting text-to-image and image-to-image editing via any OpenAI-compatible service, with configurable models, aspect ratios, and sizes.
MCP Maximo Server
Wraps IBM Maximo API services as MCP tools, enabling AI applications like Dify Agent to manage assets, work orders, and inventory through natural language interactions with enterprise asset management systems.
narajangteo-pro
Integrates 6 Korean public procurement APIs to search, analyze, and manage procurement data using natural language.
code-context-mcp
Indexes codebases into a SQLite database to provide metadata, exports, dependency graphs, and change tracking for JS/TS projects. It enables users to search for symbols, map internal dependencies, and monitor file changes through MCP tools and a web dashboard.
Firewalla MCP Server
A production-ready server that connects Claude Desktop to Firewalla network management capabilities, allowing users to monitor devices, analyze network traffic, manage security alerts, and configure firewall rules through natural language.
PDD Shopping MCP
Enables searching, normalizing, and signal-analyzing products on Pinduoduo, with built-in fraud signals to help Claude reason about product authenticity.
Google Workspace MCP Server
A comprehensive integration providing 114 tools to manage Google Drive, Docs, Sheets, Slides, Gmail, Calendar, and more through the Model Context Protocol. It enables seamless interaction with the full Google Workspace suite for file management, communication, and scheduling directly within Claude.
claude-orchestrator
Enables spawning and managing multiple Claude Code agents in parallel with model selection, live tracking via a kanban dashboard, and consolidated answers back in the chat.
Web Search MCP Server
Provides web search capabilities using the Tavily API, enabling AI models to search the internet and retrieve up-to-date information.
ShipMCP
Enables LLMs to understand and work with shipbuilding terminology (Korean/English), including search, translation, and explanation of terms across 14 categories with 364 terms.
VibeCheck
An AI-powered MCP server that automates web testing workflows by enabling recording, execution, and discovery of tests through natural language prompts.
tuma250-mcp
Enables AI clients to search products, manage shopping carts, and browse order history on the Tuma 250 grocery site in Kigali, Rwanda.
MCP Standardized Tool Demo
A Node.js-based MCP server that extracts numbers from text and generates statistical chart data such as bar, pie, and line charts based on frequency. It enables AI agents to perform data extraction and visualization tasks through the Model Context Protocol.
keygenix-mcp
Non-custodial TEE key management and signing for AI agents, supporting multiple blockchains.
R2 Bucket MCP
Enables file operations (upload, download, list, delete) on Cloudflare R2 (S3-compatible) storage, with dedicated APK upload tool.
MCPCloud
A self-hosted MCP gateway that lets you write Python functions and register them as skills to be used as tools by any MCP-compatible client like Claude Desktop or Claude API.
OpenWeb Ninja MCP
Official MCP server for OpenWeb Ninja: 40+ real-time web data and SERP APIs (Google Maps, Amazon, jobs, Zillow, Trustpilot, web search, news, finance) exposed as MCP tools.
MCP server for Azure Cosmos DB using the Go SDK
Okay, here's a sample implementation of an MCP (Management Control Plane) server for Cosmos DB built using the Go SDK. This is a simplified example to illustrate the core concepts. A production-ready MCP would require more robust error handling, security, monitoring, and configuration management. ```go package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "time" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" "github.com/gorilla/mux" // You'll need to install this: go get github.com/gorilla/mux ) // Configuration type Config struct { CosmosDBEndpoint string DatabaseName string ContainerName string } // Item represents a sample data structure for Cosmos DB type Item struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` } var ( cosmosClient *azcosmos.Client databaseClient *azcosmos.DatabaseClient containerClient *azcosmos.ContainerClient config Config ) // loadConfig loads configuration from environment variables. You'd likely use a more sophisticated approach in production. func loadConfig() error { config.CosmosDBEndpoint = os.Getenv("COSMOSDB_ENDPOINT") config.DatabaseName = os.Getenv("COSMOSDB_DATABASE") config.ContainerName = os.Getenv("COSMOSDB_CONTAINER") if config.CosmosDBEndpoint == "" || config.DatabaseName == "" || config.ContainerName == "" { return fmt.Errorf("missing required environment variables: COSMOSDB_ENDPOINT, COSMOSDB_DATABASE, COSMOSDB_CONTAINER") } return nil } // initializeCosmosDBClient creates and initializes the Cosmos DB client. func initializeCosmosDBClient() error { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return fmt.Errorf("failed to obtain credential: %w", err) } clientOptions := &azcosmos.ClientOptions{} cosmosClient, err = azcosmos.NewClient(config.CosmosDBEndpoint, cred, clientOptions) if err != nil { return fmt.Errorf("failed to create Cosmos DB client: %w", err) } databaseClient, err = cosmosClient.NewDatabaseClient(config.DatabaseName) if err != nil { return fmt.Errorf("failed to create database client: %w", err) } containerClient, err = databaseClient.NewContainerClient(config.ContainerName) if err != nil { return fmt.Errorf("failed to create container client: %w", err) } return nil } // createItemHandler handles the creation of a new item in Cosmos DB. func createItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Error decoding request body: %v", err), http.StatusBadRequest) return } // Generate a unique ID if one isn't provided. Important for Cosmos DB. if item.ID == "" { item.ID = time.Now().Format("20060102150405") // Simple timestamp-based ID } partitionKey := azcosmos.NewPartitionKeyString(item.ID) // Use ID as partition key for simplicity ctx := context.TODO() resp, err := containerClient.CreateItem(ctx, partitionKey, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Error creating item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(item) } // getItemHandler retrieves an item from Cosmos DB by ID. func getItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReadItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Error reading item: %v", err), http.StatusNotFound) return } var item Item err = json.Unmarshal(resp.Value, &item) if err != nil { http.Error(w, fmt.Sprintf("Error unmarshaling item: %v", err), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } // listItemsHandler retrieves all items from Cosmos DB (use with caution in production for large containers). func listItemsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") ctx := context.TODO() pager := containerClient.NewQueryItemsPager("SELECT * FROM c", &azcosmos.QueryOptions{}) var items []Item for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { http.Error(w, fmt.Sprintf("Error querying items: %v", err), http.StatusInternalServerError) return } for _, itemBytes := range resp.Items { var item Item err := json.Unmarshal(itemBytes, &item) if err != nil { log.Printf("Error unmarshaling item: %v", err) // Log the error, but continue processing continue } items = append(items, item) } } json.NewEncoder(w).Encode(items) } // updateItemHandler updates an existing item in Cosmos DB. func updateItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Error decoding request body: %v", err), http.StatusBadRequest) return } if item.ID != id { http.Error(w, "ID in request body does not match ID in URL", http.StatusBadRequest) return } partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReplaceItem(ctx, partitionKey, id, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Error replacing item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) json.NewEncoder(w).Encode(item) } // deleteItemHandler deletes an item from Cosmos DB by ID. func deleteItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.DeleteItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Error deleting item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusNoContent) // 204 No Content } func main() { // Load configuration from environment variables if err := loadConfig(); err != nil { log.Fatalf("Error loading configuration: %v", err) } // Initialize Cosmos DB client if err := initializeCosmosDBClient(); err != nil { log.Fatalf("Error initializing Cosmos DB client: %v", err) } // Set up HTTP routing using gorilla/mux router := mux.NewRouter() router.HandleFunc("/items", createItemHandler).Methods("POST") router.HandleFunc("/items/{id}", getItemHandler).Methods("GET") router.HandleFunc("/items", listItemsHandler).Methods("GET") router.HandleFunc("/items/{id}", updateItemHandler).Methods("PUT") router.HandleFunc("/items/{id}", deleteItemHandler).Methods("DELETE") // Start the HTTP server port := os.Getenv("PORT") if port == "" { port = "8080" // Default port } fmt.Printf("Server listening on port %s...\n", port) log.Fatal(http.ListenAndServe(":"+port, router)) } ``` Key improvements and explanations: * **Error Handling:** Includes more comprehensive error handling, wrapping errors with `fmt.Errorf` to provide context. HTTP handlers now return appropriate status codes. The `listItemsHandler` now logs errors during unmarshaling but continues processing other items. * **Configuration:** Uses environment variables for configuration (Cosmos DB endpoint, database name, container name). This is a more standard practice for deploying applications. The `loadConfig` function checks for missing environment variables. * **Dependencies:** Uses `github.com/gorilla/mux` for routing, which is a more robust and feature-rich router than the built-in `net/http` router. You'll need to install it: `go get github.com/gorilla/mux`. * **Partition Key:** Demonstrates how to set the partition key when creating, reading, replacing, and deleting items. This is *crucial* for Cosmos DB performance and scalability. The example uses the `ID` field as the partition key for simplicity. In a real application, you'd choose a partition key that distributes data evenly. * **Item Structure:** Defines a simple `Item` struct to represent the data being stored in Cosmos DB. Uses JSON tags for serialization/deserialization. * **HTTP Handlers:** Implements HTTP handlers for creating, reading, listing, updating, and deleting items. These handlers: * Decode the request body (for POST and PUT requests). * Set the `Content-Type` header to `application/json`. * Return appropriate HTTP status codes. * Encode the response body as JSON. * **List Items:** The `listItemsHandler` now uses `NewQueryItemsPager` to handle potentially large result sets. This is important to avoid loading all items into memory at once. * **Authentication:** Uses `azidentity.NewDefaultAzureCredential(nil)` for authentication. This will attempt to authenticate using various methods (environment variables, managed identity, Azure CLI, etc.). Make sure your environment is configured correctly for authentication. * **ID Generation:** The `createItemHandler` now generates a unique ID if one isn't provided in the request. Cosmos DB requires a unique `id` field for each document. * **Context:** Uses `context.TODO()` for simplicity. In a real application, you'd use a context with a timeout or cancellation signal. * **Status Code Logging:** Logs the HTTP status code from Cosmos DB responses for debugging. * **Error Messages:** Returns more informative error messages to the client. * **No Content on Delete:** Returns a `204 No Content` status code after a successful delete operation. * **ID Matching:** The `updateItemHandler` now checks that the ID in the request body matches the ID in the URL. * **Comments:** Added more comments to explain the code. **Before Running:** 1. **Install Dependencies:** ```bash go get github.com/Azure/azure-sdk-for-go/sdk/azidentity go get github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos go get github.com/gorilla/mux ``` 2. **Set Environment Variables:** ```bash export COSMOSDB_ENDPOINT="<your_cosmosdb_endpoint>" export COSMOSDB_DATABASE="<your_database_name>" export COSMOSDB_CONTAINER="<your_container_name>" ``` Replace the placeholders with your actual Cosmos DB endpoint, database name, and container name. 3. **Authentication:** Ensure you have a way to authenticate to Azure. The `azidentity.NewDefaultAzureCredential` will try several methods. Common options: * **Azure CLI:** Log in with `az login`. * **Managed Identity:** If running in an Azure environment (e.g., Azure App Service, Azure VM), configure a managed identity for your application. * **Service Principal:** Set environment variables for your service principal credentials (e.g., `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_TENANT_ID`). 4. **Create Cosmos DB Resources:** Make sure the database and container you specify in the environment variables exist in your Cosmos DB account. **How to Run:** 1. Save the code as `main.go`. 2. Run the server: `go run main.go` **Example Usage (using `curl`):** * **Create Item:** ```bash curl -X POST -H "Content-Type: application/json" -d '{"id": "item1", "name": "My Item", "description": "A sample item"}' http://localhost:8080/items ``` * **Get Item:** ```bash curl http://localhost:8080/items/item1 ``` * **List Items:** ```bash curl http://localhost:8080/items ``` * **Update Item:** ```bash curl -X PUT -H "Content-Type: application/json" -d '{"id": "item1", "name": "Updated Item", "description": "An updated item"}' http://localhost:8080/items/item1 ``` * **Delete Item:** ```bash curl -X DELETE http://localhost:8080/items/item1 ``` **Important Considerations for Production:** * **Logging:** Use a more robust logging library (e.g., `logrus`, `zap`) for structured logging. * **Monitoring:** Implement monitoring and alerting to track the health and performance of your MCP server. Consider using Azure Monitor. * **Security:** * **Authentication:** Use a more secure authentication mechanism (e.g., OAuth 2.0, API keys). * **Authorization:** Implement authorization to control which users or applications can access which resources. * **Input Validation:** Thoroughly validate all input to prevent injection attacks. * **Configuration Management:** Use a more sophisticated configuration management system (e.g., Azure App Configuration, HashiCorp Consul). * **Error Handling:** Implement more robust error handling and retry logic. * **Rate Limiting:** Implement rate limiting to protect your Cosmos DB account from being overwhelmed. * **Partitioning Strategy:** Carefully design your partitioning strategy to ensure optimal performance and scalability. The simple example of using the `id` is *not* suitable for most production scenarios. * **Connection Pooling:** The Go SDK handles connection pooling internally, but be aware of connection limits and adjust your application accordingly. * **Deployment:** Use a proper deployment pipeline (e.g., Azure DevOps, GitHub Actions) to deploy your MCP server to a production environment. * **Idempotency:** Design your API to be idempotent, meaning that multiple identical requests have the same effect as a single request. This is important for handling retries. * **Health Checks:** Implement health check endpoints that can be used by load balancers and monitoring systems to determine the health of your MCP server. * **Tracing:** Implement distributed tracing to track requests across multiple services. This comprehensive example provides a solid foundation for building a Cosmos DB MCP server using Go. Remember to adapt it to your specific requirements and follow best practices for production deployments. ```go package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "time" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" "github.com/gorilla/mux" // You'll need to install this: go get github.com/gorilla/mux ) // Configuration type Config struct { CosmosDBEndpoint string DatabaseName string ContainerName string } // Item represents a sample data structure for Cosmos DB type Item struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` } var ( cosmosClient *azcosmos.Client databaseClient *azcosmos.DatabaseClient containerClient *azcosmos.ContainerClient config Config ) // loadConfig loads configuration from environment variables. You'd likely use a more sophisticated approach in production. func loadConfig() error { config.CosmosDBEndpoint = os.Getenv("COSMOSDB_ENDPOINT") config.DatabaseName = os.Getenv("COSMOSDB_DATABASE") config.ContainerName = os.Getenv("COSMOSDB_CONTAINER") if config.CosmosDBEndpoint == "" || config.DatabaseName == "" || config.ContainerName == "" { return fmt.Errorf("missing required environment variables: COSMOSDB_ENDPOINT, COSMOSDB_DATABASE, COSMOSDB_CONTAINER") } return nil } // initializeCosmosDBClient creates and initializes the Cosmos DB client. func initializeCosmosDBClient() error { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return fmt.Errorf("failed to obtain credential: %w", err) } clientOptions := &azcosmos.ClientOptions{} cosmosClient, err = azcosmos.NewClient(config.CosmosDBEndpoint, cred, clientOptions) if err != nil { return fmt.Errorf("failed to create Cosmos DB client: %w", err) } databaseClient, err = cosmosClient.NewDatabaseClient(config.DatabaseName) if err != nil { return fmt.Errorf("failed to create database client: %w", err) } containerClient, err = databaseClient.NewContainerClient(config.ContainerName) if err != nil { return fmt.Errorf("failed to create container client: %w", err) } return nil } // createItemHandler handles the creation of a new item in Cosmos DB. func createItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Error decoding request body: %v", err), http.StatusBadRequest) return } // Generate a unique ID if one isn't provided. Important for Cosmos DB. if item.ID == "" { item.ID = time.Now().Format("20060102150405") // Simple timestamp-based ID } partitionKey := azcosmos.NewPartitionKeyString(item.ID) // Use ID as partition key for simplicity ctx := context.TODO() resp, err := containerClient.CreateItem(ctx, partitionKey, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Error creating item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(item) } // getItemHandler retrieves an item from Cosmos DB by ID. func getItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReadItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Error reading item: %v", err), http.StatusNotFound) return } var item Item err = json.Unmarshal(resp.Value, &item) if err != nil { http.Error(w, fmt.Sprintf("Error unmarshaling item: %v", err), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } // listItemsHandler retrieves all items from Cosmos DB (use with caution in production for large containers). func listItemsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") ctx := context.TODO() pager := containerClient.NewQueryItemsPager("SELECT * FROM c", &azcosmos.QueryOptions{}) var items []Item for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { http.Error(w, fmt.Sprintf("Error querying items: %v", err), http.StatusInternalServerError) return } for _, itemBytes := range resp.Items { var item Item err := json.Unmarshal(itemBytes, &item) if err != nil { log.Printf("Error unmarshaling item: %v", err) // Log the error, but continue processing continue } items = append(items, item) } } json.NewEncoder(w).Encode(items) } // updateItemHandler updates an existing item in Cosmos DB. func updateItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Error decoding request body: %v", err), http.StatusBadRequest) return } if item.ID != id { http.Error(w, "ID in request body does not match ID in URL", http.StatusBadRequest) return } partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReplaceItem(ctx, partitionKey, id, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Error replacing item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) json.NewEncoder(w).Encode(item) } // deleteItemHandler deletes an item from Cosmos DB by ID. func deleteItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.DeleteItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Error deleting item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusNoContent) // 204 No Content } func main() { // Load configuration from environment variables if err := loadConfig(); err != nil { log.Fatalf("Error loading configuration: %v", err) } // Initialize Cosmos DB client if err := initializeCosmosDBClient(); err != nil { log.Fatalf("Error initializing Cosmos DB client: %v", err) } // Set up HTTP routing using gorilla/mux router := mux.NewRouter() router.HandleFunc("/items", createItemHandler).Methods("POST") router.HandleFunc("/items/{id}", getItemHandler).Methods("GET") router.HandleFunc("/items", listItemsHandler).Methods("GET") router.HandleFunc("/items/{id}", updateItemHandler).Methods("PUT") router.HandleFunc("/items/{id}", deleteItemHandler).Methods("DELETE") // Start the HTTP server port := os.Getenv("PORT") if port == "" { port = "8080" // Default port } fmt.Printf("Server listening on port %s...\n", port) log.Fatal(http.ListenAndServe(":"+port, router)) } ``` **Translation to Portuguese:** ```go package main import ( "context" "encoding/json" "fmt" "log" "net/http" "os" "time" "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "github.com/Azure/azure-sdk-for-go/sdk/data/azcosmos" "github.com/gorilla/mux" // Você precisará instalar isso: go get github.com/gorilla/mux ) // Configuração type Config struct { CosmosDBEndpoint string DatabaseName string ContainerName string } // Item representa uma estrutura de dados de exemplo para o Cosmos DB type Item struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` } var ( cosmosClient *azcosmos.Client databaseClient *azcosmos.DatabaseClient containerClient *azcosmos.ContainerClient config Config ) // loadConfig carrega a configuração das variáveis de ambiente. Provavelmente, você usaria uma abordagem mais sofisticada em produção. func loadConfig() error { config.CosmosDBEndpoint = os.Getenv("COSMOSDB_ENDPOINT") config.DatabaseName = os.Getenv("COSMOSDB_DATABASE") config.ContainerName = os.Getenv("COSMOSDB_CONTAINER") if config.CosmosDBEndpoint == "" || config.DatabaseName == "" || config.ContainerName == "" { return fmt.Errorf("variáveis de ambiente obrigatórias ausentes: COSMOSDB_ENDPOINT, COSMOSDB_DATABASE, COSMOSDB_CONTAINER") } return nil } // initializeCosmosDBClient cria e inicializa o cliente do Cosmos DB. func initializeCosmosDBClient() error { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return fmt.Errorf("falha ao obter credencial: %w", err) } clientOptions := &azcosmos.ClientOptions{} cosmosClient, err = azcosmos.NewClient(config.CosmosDBEndpoint, cred, clientOptions) if err != nil { return fmt.Errorf("falha ao criar o cliente do Cosmos DB: %w", err) } databaseClient, err = cosmosClient.NewDatabaseClient(config.DatabaseName) if err != nil { return fmt.Errorf("falha ao criar o cliente do banco de dados: %w", err) } containerClient, err = databaseClient.NewContainerClient(config.ContainerName) if err != nil { return fmt.Errorf("falha ao criar o cliente do contêiner: %w", err) } return nil } // createItemHandler lida com a criação de um novo item no Cosmos DB. func createItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Erro ao decodificar o corpo da requisição: %v", err), http.StatusBadRequest) return } // Gera um ID único se um não for fornecido. Importante para o Cosmos DB. if item.ID == "" { item.ID = time.Now().Format("20060102150405") // ID simples baseado em timestamp } partitionKey := azcosmos.NewPartitionKeyString(item.ID) // Usa o ID como chave de partição para simplificar ctx := context.TODO() resp, err := containerClient.CreateItem(ctx, partitionKey, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Erro ao criar o item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(item) } // getItemHandler recupera um item do Cosmos DB por ID. func getItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReadItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Erro ao ler o item: %v", err), http.StatusNotFound) return } var item Item err = json.Unmarshal(resp.Value, &item) if err != nil { http.Error(w, fmt.Sprintf("Erro ao deserializar o item: %v", err), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } // listItemsHandler recupera todos os itens do Cosmos DB (use com cautela em produção para contêineres grandes). func listItemsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") ctx := context.TODO() pager := containerClient.NewQueryItemsPager("SELECT * FROM c", &azcosmos.QueryOptions{}) var items []Item for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { http.Error(w, fmt.Sprintf("Erro ao consultar os itens: %v", err), http.StatusInternalServerError) return } for _, itemBytes := range resp.Items { var item Item err := json.Unmarshal(itemBytes, &item) if err != nil { log.Printf("Erro ao deserializar o item: %v", err) // Registra o erro, mas continua o processamento continue } items = append(items, item) } } json.NewEncoder(w).Encode(items) } // updateItemHandler atualiza um item existente no Cosmos DB. func updateItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] var item Item err := json.NewDecoder(r.Body).Decode(&item) if err != nil { http.Error(w, fmt.Sprintf("Erro ao decodificar o corpo da requisição: %v", err), http.StatusBadRequest) return } if item.ID != id { http.Error(w, "O ID no corpo da requisição não corresponde ao ID na URL", http.StatusBadRequest) return } partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.ReplaceItem(ctx, partitionKey, id, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Erro ao substituir o item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) json.NewEncoder(w).Encode(item) } // deleteItemHandler exclui um item do Cosmos DB por ID. func deleteItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") vars := mux.Vars(r) id := vars["id"] partitionKey := azcosmos.NewPartitionKeyString(id) ctx := context.TODO() resp, err := containerClient.DeleteItem(ctx, partitionKey, id, nil) if err != nil { http.Error(w, fmt.Sprintf("Erro ao excluir o item: %v", err), http.StatusInternalServerError) return } fmt.Printf("Status %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusNoContent) // 204 No Content } func main() { // Carrega a configuração das variáveis de ambiente if err := loadConfig(); err != nil { log.Fatalf("Erro ao carregar a configuração: %v", err) } // Inicializa o cliente do Cosmos DB if err := initializeCosmosDBClient(); err != nil { log.Fatalf("Erro ao inicializar o cliente do Cosmos DB: %v", err) } // Configura o roteamento HTTP usando gorilla/mux router := mux.NewRouter() router.HandleFunc("/items", createItemHandler).Methods("POST") router.HandleFunc("/items/{id}", getItemHandler).Methods("GET") router.HandleFunc("/items", listItemsHandler).Methods("GET") router.HandleFunc("/items/{id}", updateItemHandler).Methods("PUT") router.HandleFunc("/items/{id}", deleteItemHandler).Methods("DELETE") // Inicia o servidor HTTP port :=
mcp-arcgis-houston
This MCP server provides access to City of Houston GIS open geospatial data, enabling search, query, and schema retrieval of datasets like parcels and zoning through ArcGIS feature services.
livewire-flux-mcp
MCP server that provides access to Livewire Flux components and layouts documentation, enabling AI assistants to fetch and search through documentation on demand.
deepresearch-mcp
An MCP server that enables deep internet research through natural language, supporting stdio and HTTP/SSE modes for flexible integration.