Discover Awesome MCP Servers

Extend your agent with 23,495 capabilities via MCP servers.

All23,495
ms-agentframework

ms-agentframework

Production-ready integration of Microsoft Agent Framework with MCP, enabling AI agents to access tools like weather queries, calculations, and Taiwan stock prices through SSE/HTTP streaming transport with Azure OpenAI GPT-4 backend.

Semrush MCP Server

Semrush MCP Server

A Cursor MCP server that provides tools and prompts for accessing various Semrush keyword-related API endpoints, enabling keyword research, analysis, and monitoring through natural language.

Advanced PocketBase MCP Server

Advanced PocketBase MCP Server

Um servidor MCP abrangente que fornece ferramentas sofisticadas para interagir com bancos de dados PocketBase. Este servidor permite operações avançadas de banco de dados, gerenciamento de esquema e manipulação de dados através do Protocolo de Contexto de Modelo (MCP).

SAP Fieldglass MCP Server by CData

SAP Fieldglass MCP Server by CData

This read-only MCP Server allows you to connect to SAP Fieldglass data from Claude Desktop through CData JDBC Drivers. Free (beta) read/write servers available at https://www.cdata.com/solutions/mcp

Teradata MCP Server

Teradata MCP Server

Enables AI agents and users to query, analyze, and manage Teradata databases through modular tools for search, data quality, administration, and data science operations. Provides comprehensive database interaction capabilities including RAG applications, feature store management, and vector operations.

Code Buddy

Code Buddy

A comprehensive MCP server that provides AI assistants with tools for file system management, Git integration, and shell command execution. It features specialized code utilities for analysis, formatting, and linting to enhance development workflows within Claude Desktop.

ActiveCampaign MCP Server

ActiveCampaign MCP Server

An MCP server that enables AI tools to interact with ActiveCampaign API, allowing contact management and tracking event analysis through natural language queries.

PubChem-MCP

PubChem-MCP

An MCP server that provides tools for querying the PubChem database for detailed information on chemical compounds, substances, bioassays, and molecular properties. It enables users to search by name, structure, or identifier to retrieve chemical classifications and cross-references through natural language.

SimplyHired MCP Server

SimplyHired MCP Server

Enables searching job listings on SimplyHired.com with customizable parameters including query, location, and search radius.

Conduit

Conduit

A bridge that exposes any GraphQL API as tools consumable by Large Language Models via the Model Context Protocol (MCP), automatically discovering and translating API capabilities with zero maintenance required.

高德地图

高德地图

高德地图

MCP TypeScript Template

MCP TypeScript Template

A production-grade TypeScript template for building Model Context Protocol (MCP) servers with declarative tools/resources, authentication, storage abstraction, and support for both local and edge deployment. Provides example echo tools and resources to demonstrate MCP server development patterns.

Google Ads MCP Server

Google Ads MCP Server

Enables programmatic management of Google Ads campaigns, allowing users to monitor performance metrics, update budgets, and toggle campaign statuses. It supports real-time analytics, top performer analysis, and reporting in CSV or JSON formats.

PostgreSQL MCP AllAccess

PostgreSQL MCP AllAccess

Enables interaction with PostgreSQL databases through a production-ready MCP server with global connection pooling, automatic AWS password rotation, and comprehensive SQL operations. Supports multiple concurrent Claude sessions while maintaining efficient connection limits to the database.

GitHub MCP Server

GitHub MCP Server

Universal Infinite Loop MCP Server

Universal Infinite Loop MCP Server

A goal-agnostic parallel orchestration framework that enables sophisticated multi-agent coordination for tasks like code generation, UI development, and research through specification-driven architecture. It utilizes wave-based generation and intelligent context management to execute complex, iterative agentic loops.

MCP Server Demo

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.

ROADrecon MCP Server

ROADrecon MCP Server

Servidor Claude MCP para realizar análises em dados ROADrecon.

basic-mcp

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.

mcp_search_images

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.

Self-Hosted EdgeOne Pages MCP Server

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.

MCP server for Azure Cosmos DB using the Go SDK

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 :=

Alibaba Cloud RDS OpenAPI MCP Server

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

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.

Pythagraph RED MCP Server

Pythagraph RED MCP Server

Enables retrieval and analysis of graph data from the Pythagraph RED API. Provides formatted tables, statistics, node/edge distributions, and comprehensive summaries for graph visualization and insights.

ComfyUI MCP Server

ComfyUI MCP Server

"generate_image" e outros fluxos de trabalho.

Google Drive MCP Server

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.

Excel MCP Server

Excel MCP Server

mcp-server

mcp-server

Tarefa para o estágio da Alaiy

JSR MCP

JSR MCP

Model Context Protocol server for the JSR (JavaScript Registry)