Discover Awesome MCP Servers
Extend your agent with 20,381 capabilities via MCP servers.
- All20,381
- 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
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.
神岛地图数据统计
Fornece acesso a dados de usuários, informações de mapas e estatísticas da plataforma Shenzhou.
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.
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.
Learn_MCP Math Server
A Model Context Protocol (MCP) server that demonstrates mathematical capabilities through a LangChain integration, allowing clients to perform math operations via the MCP protocol.
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.
Ghost MCP Server
An implementation of the Model Context Protocol Server that allows AI clients like Cursor or Claude Desktop to manage Ghost CMS blogs by exposing capabilities like creating posts, adding tags, and uploading images.
Spinitron API MCP Server
Enables interaction with Spinitron's radio playlist management and broadcasting data through a Multi-Agent Conversation Protocol interface, allowing users to query and manage radio station playlists, spins, and other broadcasting data via natural language.
MCP Server Demo
A simple demonstration project for the Model Control Protocol (MCP) server that provides tools for AI assistants to fetch news articles, perform calculations, retrieve weather data, and generate personalized greetings.
Substrate
A foundation layer for building production-grade Model Context Protocol (MCP) servers with base classes, documentation, and consistent implementation patterns.
basic-mcp
Provides a suite of deterministic tools for time calculations, math, and string manipulation that LLMs often struggle to perform accurately. It also includes utilities for secure randomness, data validation, and basic network operations like DNS lookups.
Aleph
Enables AI assistants to analyze documents larger than their context window by loading files into RAM and querying them via search, navigation, and Python execution tools. Supports recursive reasoning to process massive datasets in chunks using sub-agents.
Zilliqa MCP Server
Provides access to Zilliqa blockchain documentation and API examples through search capabilities and examples in multiple programming languages.
Sidvy MCP Server
Provides AI tools with full access to the Sidvy note-taking API, enabling management of notes, todos, groups, and workspaces with search, filtering, and real-time synchronization capabilities.
Flight Control MCP Server
Provides read-only access to query and retrieve information about devices, fleets, events, and configurations managed by Flight Control through a safe integration layer supporting filtering and selector-based queries.
TypeScript Package Introspector (MCP Server)
Video Metadata MCP Server
Manages sports video metadata with CRUD operations for game information, teams, scores, and statistics. Enables advanced search filtering by game type, teams, league, season, and date ranges through PostgreSQL integration.
Mailchimp MCP Server
n8n MCP Server
Enables AI models to manage n8n workflow automation through a standardized interface. Supports creating, reading, updating, and deleting workflows with comprehensive access to workflow nodes, connections, and configurations.
Web3 Research MCP
Enables deep research into cryptocurrency tokens by gathering data from multiple sources like CoinGecko and DeFiLlama to generate structured reports. It allows users to track research progress, fetch web content, and manage resources locally for comprehensive crypto analysis.
WoT Blitz MCP Server
Provides AI assistants with access to authentic World of Tanks Blitz game data including tank statistics, armor values, map terrain features, equipment, crew skills, and camouflages parsed directly from local game files.
vap-mcp-server
Execution control layer for AI agents - Reserve, execute, burn/refund pattern for media generation
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 :=
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.
deep-filesystem-tree
Uma implementação do Protocolo de Contexto de Modelo (MCP) que oferece visualização e manipulação profunda de árvores de sistema de arquivos. Esta ferramenta permite a navegação e o gerenciamento eficientes de estruturas de diretórios complexas, aprimorando os fluxos de trabalho de desenvolvimento com operações de sistema de arquivos alimentadas por IA. Compatível com
mcp_search_images
Um serviço de busca baseado em múltiplas APIs de imagem e capacidades de geração de ícones, especificamente projetado para integração com o serviço Cursor MCP. Suporta busca de imagens, download e ícones gerados por IA.
SMART-E2B
Enables secure execution of JavaScript and Python code in cloud-based E2B sandboxes with integrated file management capabilities, allowing Claude to run and test code safely in isolated environments.
Self-Hosted EdgeOne Pages MCP Server
Enables AI assistants to deploy and manage static websites directly on EdgeOne Pages through a self-hosted Model Context Protocol solution. It simplifies web hosting by allowing natural language commands to handle site deployment and KV storage management.
Alibaba Cloud RDS OpenAPI MCP Server
Um servidor que fornece gerenciamento e conectividade para os serviços de banco de dados RDS da Alibaba Cloud via OpenAPI, permitindo que os usuários criem, consultem e modifiquem instâncias RDS através da integração com o MCP.
DataMaker MCP Server
Enables AI models to generate synthetic data, manage templates and connections, push data to destinations, and execute Python scripts using DataMaker's data generation platform. Automatically handles large datasets by storing them to S3 with secure access links.