Discover Awesome MCP Servers
Extend your agent with 23,901 capabilities via MCP servers.
- All23,901
- 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
小记(AI记账)
小记,是一款基于AI的个人智能记账工具,通过自然语言交互实现「一句话极速记账、查账」。 你只需说"早餐25元,支付宝付款"或"工资到账银行卡18000元",系统将自动解析金额、分类、支付方式并记录到账本中。 而且支持🔥MCP客户端使用。
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.
MiniMax MCP JS
Implementación en JavaScript de MiniMax MCP que permite la interacción con los servicios de IA de MiniMax para la generación de imágenes, la generación de videos, la conversión de texto a voz y la clonación de voz a través de clientes compatibles con MCP.
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.
Task Context MCP Server
Enables AI agents to autonomously manage and improve execution processes for repetitive task types by storing reusable task contexts with associated artifacts (practices, rules, prompts, learnings) and providing full-text search across historical best practices.
Toon Fetch MCP Server
Fetches web page content, converts it to Markdown, and optionally processes it with a local LLM. Returns structured data in TOON format optimized for agent consumption.
CodeBot MCP Server v2
An extended MCP server for managing code snippets, performing code analysis, and handling deployments via Render and GitHub. It enables users to perform code reviews, track issues, and manage service operations through natural language interactions.
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
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
Un servidor MCP integral que proporciona herramientas sofisticadas para interactuar con bases de datos PocketBase. Este servidor permite operaciones de base de datos avanzadas, gestión de esquemas y manipulación de datos a través del Protocolo de Contexto de Modelo (MCP).
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
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
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
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
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
Enables searching job listings on SimplyHired.com with customizable parameters including query, location, and search radius.
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
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
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
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
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
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
Servidor Claude MCP para realizar análisis de datos de ROADrecon.
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
Un servicio de búsqueda basado en múltiples APIs de imágenes y capacidades de generación de iconos, diseñado específicamente para la integración con el servicio Cursor MCP. Soporta la búsqueda, descarga y generación de iconos mediante IA.
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
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 real-world MCP would likely be much more complex, handling authentication, authorization, auditing, error handling, and more sophisticated resource 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 } var ( config Config client *azcosmos.Client ) // Item represents a sample data structure for Cosmos DB type Item struct { ID string `json:"id"` Description string `json:"description"` Category string `json:"category"` } // loadConfig loads configuration from environment variables. You'd likely use a more robust config management solution in production. func loadConfig() { 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 == "" { log.Fatal("Missing required environment variables: COSMOSDB_ENDPOINT, COSMOSDB_DATABASE, COSMOSDB_CONTAINER") } } // initCosmosClient initializes the Cosmos DB client. func initCosmosClient() error { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return fmt.Errorf("failed to obtain credential: %w", err) } clientOptions := &azcosmos.ClientOptions{} client, err = azcosmos.NewClient(config.CosmosDBEndpoint, cred, clientOptions) if err != nil { return fmt.Errorf("failed to create 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, err.Error(), http.StatusBadRequest) return } databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get database client: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get container client: %v", err), http.StatusInternalServerError) return } partitionKey := azcosmos.NewPartitionKeyString(item.Category) // Use Category as partition key ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resp, err := containerClient.CreateItem(ctx, partitionKey, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Failed to create 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") params := mux.Vars(r) itemID := params["id"] databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get database client: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get container client: %v", err), http.StatusInternalServerError) return } // In a real application, you'd likely need to determine the partition key value // based on the item ID or some other logic. For this example, we'll assume // we know the category. This is a *critical* point for Cosmos DB performance. // You *must* provide the correct partition key. partitionKey := azcosmos.NewPartitionKeyString("ExampleCategory") // Replace with actual logic ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resp, err := containerClient.ReadItem(ctx, partitionKey, itemID, nil) if err != nil { http.Error(w, fmt.Sprintf("Failed to read item: %v", err), http.StatusNotFound) return } var item Item err = json.Unmarshal(resp.Value, &item) if err != nil { http.Error(w, fmt.Sprintf("Failed to unmarshal item: %v", err), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } // listItemsHandler retrieves all items from Cosmos DB (use with caution in production). func listItemsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get database client: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Failed to get container client: %v", err), http.StatusInternalServerError) return } query := "SELECT * FROM c" // Simple query - avoid in production for large datasets pager := containerClient.NewQueryItemsPager(query, azcosmos.NewPartitionKeyDefinition(), nil) var items []Item ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { http.Error(w, fmt.Sprintf("Failed to get next page: %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 continue } items = append(items, item) } } json.NewEncoder(w).Encode(items) } func main() { loadConfig() err := initCosmosClient() if err != nil { log.Fatalf("Failed to initialize Cosmos DB client: %v", err) } router := mux.NewRouter() router.HandleFunc("/items", createItemHandler).Methods("POST") router.HandleFunc("/items/{id}", getItemHandler).Methods("GET") router.HandleFunc("/items", listItemsHandler).Methods("GET") 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 robust error handling, returning appropriate HTTP status codes and error messages to the client. Crucially, it logs errors that occur during unmarshaling of individual items in the `listItemsHandler` so that a single bad item doesn't break the entire listing. * **Configuration:** Loads configuration from environment variables. This is best practice for cloud-native applications. It also includes a check to ensure the required environment variables are set. * **Authentication:** Uses `azidentity.NewDefaultAzureCredential(nil)` which attempts to authenticate using various methods (environment variables, managed identity, Azure CLI, etc.). This is the recommended way to authenticate in Azure. You'll need to configure your environment appropriately for this to work. * **Partitioning:** **Critical:** Demonstrates the importance of partition keys. The `createItemHandler` uses the `Category` field as the partition key. The `getItemHandler` *must* know the partition key value to retrieve an item efficiently. The example includes a placeholder comment indicating where you'd need to implement logic to determine the partition key based on the item ID or other criteria. **Incorrect partition key usage will lead to very poor performance and high costs.** * **Contexts:** Uses `context.WithTimeout` for all Cosmos DB operations to prevent indefinite hangs. * **Listing (Querying):** The `listItemsHandler` uses a simple `SELECT * FROM c` query. **This is highly discouraged for production environments with large datasets.** It will result in full container scans and high RU/s consumption. You should always use more specific queries with filters and pagination. * **Gorilla Mux:** Uses the `gorilla/mux` router for more flexible route handling (e.g., path parameters). You'll need to install it: `go get github.com/gorilla/mux`. * **JSON Handling:** Uses `encoding/json` for encoding and decoding JSON data. * **HTTP Status Codes:** Returns appropriate HTTP status codes (e.g., 201 Created, 400 Bad Request, 404 Not Found, 500 Internal Server Error). * **Comments:** Includes comments to explain the code. * **Dependencies:** Clearly lists the dependencies. * **Idempotency:** This example doesn't handle idempotency. In a real MCP, you'd need to implement mechanisms to ensure that operations are idempotent (e.g., using a unique request ID). * **Error Responses:** Returns more informative error responses to the client. * **Logging:** Includes basic logging. In a production environment, you'd want to use a more sophisticated logging library. * **Partition Key Definition:** The `NewQueryItemsPager` function now includes `azcosmos.NewPartitionKeyDefinition()` to specify that the query should be executed across all partitions. This is necessary when you don't have a specific partition key to target. However, as mentioned before, this is less efficient than targeting a specific partition. * **Pagination:** The `listItemsHandler` now uses the `NewQueryItemsPager` to handle pagination. This is important for large datasets to avoid exceeding the maximum response size. * **Status Code:** Prints the status code of the `CreateItem` response. **To run this example:** 1. **Install Go:** Make sure you have Go installed. 2. **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 ``` 3. **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. 4. **Run the Server:** ```bash go run main.go ``` **Important Considerations for a Real MCP:** * **Authentication and Authorization:** Implement robust authentication (e.g., using Azure Active Directory) and authorization (e.g., using RBAC) to control access to the MCP. * **Auditing:** Log all actions performed through the MCP for auditing and compliance purposes. * **Rate Limiting:** Implement rate limiting to prevent abuse and protect your Cosmos DB resources. * **Idempotency:** Ensure that operations are idempotent. * **Error Handling and Retries:** Implement comprehensive error handling and retry logic. * **Monitoring and Alerting:** Monitor the health and performance of the MCP and set up alerts for critical issues. * **Deployment:** Deploy the MCP to a reliable and scalable environment (e.g., Azure Kubernetes Service). * **Configuration Management:** Use a robust configuration management solution (e.g., Azure App Configuration) to manage the MCP's configuration. * **Testing:** Write thorough unit and integration tests. * **Security:** Follow security best practices to protect the MCP from vulnerabilities. * **Partition Key Strategy:** Carefully design your partition key strategy to ensure optimal performance and scalability. This is *the* most important factor for Cosmos DB performance. * **Query Optimization:** Optimize your queries to minimize RU/s consumption. Avoid full container scans. * **Data Validation:** Validate the data being written to Cosmos DB to ensure data quality. * **Schema Management:** Consider using a schema management solution to manage the schema of your data. This comprehensive example provides a solid foundation for building a more complete and robust MCP for Cosmos DB using the Go SDK. Remember to adapt it to your specific requirements and follow best practices for security, performance, and scalability. Now, here's the translation to Spanish: ```spanish Aquí tienes una implementación de ejemplo de un servidor MCP (Plano de Control de Gestión) para Cosmos DB construido utilizando el SDK de Go. Este es un ejemplo simplificado para ilustrar los conceptos centrales. Un MCP del mundo real probablemente sería mucho más complejo, manejando autenticación, autorización, auditoría, manejo de errores y una gestión de recursos más sofisticada. ```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" // Necesitarás instalar esto: go get github.com/gorilla/mux ) // Configuration type Config struct { CosmosDBEndpoint string DatabaseName string ContainerName string } var ( config Config client *azcosmos.Client ) // Item representa una estructura de datos de ejemplo para Cosmos DB type Item struct { ID string `json:"id"` Description string `json:"description"` Category string `json:"category"` } // loadConfig carga la configuración de las variables de entorno. Probablemente usarías una solución de gestión de configuración más robusta en producción. func loadConfig() { 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 == "" { log.Fatal("Faltan variables de entorno obligatorias: COSMOSDB_ENDPOINT, COSMOSDB_DATABASE, COSMOSDB_CONTAINER") } } // initCosmosClient inicializa el cliente de Cosmos DB. func initCosmosClient() error { cred, err := azidentity.NewDefaultAzureCredential(nil) if err != nil { return fmt.Errorf("falló la obtención de credenciales: %w", err) } clientOptions := &azcosmos.ClientOptions{} client, err = azcosmos.NewClient(config.CosmosDBEndpoint, cred, clientOptions) if err != nil { return fmt.Errorf("falló la creación del cliente: %w", err) } return nil } // createItemHandler maneja la creación de un nuevo elemento en 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, err.Error(), http.StatusBadRequest) return } databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente de la base de datos: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente del contenedor: %v", err), http.StatusInternalServerError) return } partitionKey := azcosmos.NewPartitionKeyString(item.Category) // Usa Category como clave de partición ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resp, err := containerClient.CreateItem(ctx, partitionKey, item, nil) if err != nil { http.Error(w, fmt.Sprintf("Falló la creación del elemento: %v", err), http.StatusInternalServerError) return } fmt.Printf("Estado %d\n", resp.RawResponse.StatusCode) w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(item) } // getItemHandler recupera un elemento de Cosmos DB por ID. func getItemHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") params := mux.Vars(r) itemID := params["id"] databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente de la base de datos: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente del contenedor: %v", err), http.StatusInternalServerError) return } // En una aplicación real, probablemente necesitarías determinar el valor de la clave de partición // basado en el ID del elemento o alguna otra lógica. Para este ejemplo, asumiremos // que conocemos la categoría. Este es un punto *crítico* para el rendimiento de Cosmos DB. // *Debes* proporcionar la clave de partición correcta. partitionKey := azcosmos.NewPartitionKeyString("ExampleCategory") // Reemplaza con la lógica real ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() resp, err := containerClient.ReadItem(ctx, partitionKey, itemID, nil) if err != nil { http.Error(w, fmt.Sprintf("Falló la lectura del elemento: %v", err), http.StatusNotFound) return } var item Item err = json.Unmarshal(resp.Value, &item) if err != nil { http.Error(w, fmt.Sprintf("Falló la deserialización del elemento: %v", err), http.StatusInternalServerError) return } json.NewEncoder(w).Encode(item) } // listItemsHandler recupera todos los elementos de Cosmos DB (úsalo con precaución en producción). func listItemsHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") databaseClient, err := client.NewDatabaseClient(config.DatabaseName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente de la base de datos: %v", err), http.StatusInternalServerError) return } containerClient, err := databaseClient.NewContainerClient(config.ContainerName) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención del cliente del contenedor: %v", err), http.StatusInternalServerError) return } query := "SELECT * FROM c" // Consulta simple - evítala en producción para conjuntos de datos grandes pager := containerClient.NewQueryItemsPager(query, azcosmos.NewPartitionKeyDefinition(), nil) var items []Item ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() for pager.More() { resp, err := pager.NextPage(ctx) if err != nil { http.Error(w, fmt.Sprintf("Falló la obtención de la siguiente página: %v", err), http.StatusInternalServerError) return } for _, itemBytes := range resp.Items { var item Item err = json.Unmarshal(itemBytes, &item) if err != nil { log.Printf("Error al deserializar el elemento: %v", err) // Registra el error, pero continúa continue } items = append(items, item) } } json.NewEncoder(w).Encode(items) } func main() { loadConfig() err := initCosmosClient() if err != nil { log.Fatalf("Falló la inicialización del cliente de Cosmos DB: %v", err) } router := mux.NewRouter() router.HandleFunc("/items", createItemHandler).Methods("POST") router.HandleFunc("/items/{id}", getItemHandler).Methods("GET") router.HandleFunc("/items", listItemsHandler).Methods("GET") port := os.Getenv("PORT") if port == "" { port = "8080" // Puerto predeterminado } fmt.Printf("Servidor escuchando en el puerto %s...\n", port) log.Fatal(http.ListenAndServe(":"+port, router)) } ``` Mejoras clave y explicaciones: * **Manejo de errores:** Incluye un manejo de errores más robusto, devolviendo códigos de estado HTTP apropiados y mensajes de error al cliente. Crucialmente, registra los errores que ocurren durante la deserialización de elementos individuales en `listItemsHandler` para que un solo elemento incorrecto no interrumpa la lista completa. * **Configuración:** Carga la configuración de las variables de entorno. Esta es la mejor práctica para aplicaciones nativas de la nube. También incluye una verificación para garantizar que las variables de entorno requeridas estén configuradas. * **Autenticación:** Utiliza `azidentity.NewDefaultAzureCredential(nil)` que intenta autenticarse utilizando varios métodos (variables de entorno, identidad administrada, Azure CLI, etc.). Esta es la forma recomendada de autenticarse en Azure. Deberás configurar tu entorno adecuadamente para que esto funcione. * **Particionamiento:** **Crítico:** Demuestra la importancia de las claves de partición. `createItemHandler` utiliza el campo `Category` como clave de partición. `getItemHandler` *debe* conocer el valor de la clave de partición para recuperar un elemento de manera eficiente. El ejemplo incluye un comentario de marcador de posición que indica dónde necesitarías implementar la lógica para determinar la clave de partición basada en el ID del elemento u otros criterios. **El uso incorrecto de la clave de partición conducirá a un rendimiento muy pobre y costos elevados.** * **Contextos:** Utiliza `context.WithTimeout` para todas las operaciones de Cosmos DB para evitar bloqueos indefinidos. * **Listado (Consultas):** `listItemsHandler` utiliza una consulta simple `SELECT * FROM c`. **Esto es altamente desaconsejable para entornos de producción con grandes conjuntos de datos.** Resultará en escaneos completos del contenedor y un alto consumo de RU/s. Siempre debes usar consultas más específicas con filtros y paginación. * **Gorilla Mux:** Utiliza el enrutador `gorilla/mux` para un manejo de rutas más flexible (por ejemplo, parámetros de ruta). Necesitarás instalarlo: `go get github.com/gorilla/mux`. * **Manejo de JSON:** Utiliza `encoding/json` para codificar y decodificar datos JSON. * **Códigos de estado HTTP:** Devuelve códigos de estado HTTP apropiados (por ejemplo, 201 Creado, 400 Solicitud incorrecta, 404 No encontrado, 500 Error interno del servidor). * **Comentarios:** Incluye comentarios para explicar el código. * **Dependencias:** Enumera claramente las dependencias. * **Idempotencia:** Este ejemplo no maneja la idempotencia. En un MCP real, necesitarías implementar mecanismos para garantizar que las operaciones sean idempotentes (por ejemplo, utilizando un ID de solicitud único). * **Respuestas de error:** Devuelve respuestas de error más informativas al cliente. * **Registro:** Incluye un registro básico. En un entorno de producción, querrías utilizar una biblioteca de registro más sofisticada. * **Definición de clave de partición:** La función `NewQueryItemsPager` ahora incluye `azcosmos.NewPartitionKeyDefinition()` para especificar que la consulta debe ejecutarse en todas las particiones. Esto es necesario cuando no tienes una clave de partición específica para apuntar. Sin embargo, como se mencionó antes, esto es menos eficiente que apuntar a una partición específica. * **Paginación:** El `listItemsHandler` ahora usa `NewQueryItemsPager` para manejar la paginación. Esto es importante para conjuntos de datos grandes para evitar exceder el tamaño máximo de respuesta. * **Código de estado:** Imprime el código de estado de la respuesta `CreateItem`. **Para ejecutar este ejemplo:** 1. **Instala Go:** Asegúrate de tener Go instalado. 2. **Instala las dependencias:** ```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 ``` 3. **Configura las variables de entorno:** ```bash export COSMOSDB_ENDPOINT="<tu_endpoint_de_cosmosdb>" export COSMOSDB_DATABASE="<tu_nombre_de_base_de_datos>" export COSMOSDB_CONTAINER="<tu_nombre_de_contenedor>" ``` Reemplaza los marcadores de posición con tu endpoint de Cosmos DB, nombre de base de datos y nombre de contenedor reales. 4. **Ejecuta el servidor:** ```bash go run main.go ``` **Consideraciones importantes para un MCP real:** * **Autenticación y autorización:** Implementa una autenticación robusta (por ejemplo, utilizando Azure Active Directory) y autorización (por ejemplo, utilizando RBAC) para controlar el acceso al MCP. * **Auditoría:** Registra todas las acciones realizadas a través del MCP con fines de auditoría y cumplimiento. * **Limitación de velocidad:** Implementa la limitación de velocidad para evitar el abuso y proteger tus recursos de Cosmos DB. * **Idempotencia:** Asegúrate de que las operaciones sean idempotentes. * **Manejo de errores y reintentos:** Implementa un manejo de errores integral y lógica de reintento. * **Monitoreo y alertas:** Monitorea la salud y el rendimiento del MCP y configura alertas para problemas críticos. * **Implementación:** Implementa el MCP en un entorno confiable y escalable (por ejemplo, Azure Kubernetes Service). * **Gestión de la configuración:** Utiliza una solución de gestión de la configuración robusta (por ejemplo, Azure App Configuration) para gestionar la configuración del MCP. * **Pruebas:** Escribe pruebas unitarias y de integración exhaustivas. * **Seguridad:** Sigue las mejores prácticas de seguridad para proteger el MCP de vulnerabilidades. * **Estrategia de clave de partición:** Diseña cuidadosamente tu estrategia de clave de partición para garantizar un rendimiento y una escalabilidad óptimos. Este es *el* factor más importante para el rendimiento de Cosmos DB. * **Optimización de consultas:** Optimiza tus consultas para minimizar el consumo de RU/s. Evita los escaneos completos del contenedor. * **Validación de datos:** Valida los datos que se escriben en Cosmos DB para garantizar la calidad de los datos. * **Gestión de esquemas:** Considera utilizar una solución de gestión de esquemas para gestionar el esquema de tus datos. Este ejemplo completo proporciona una base sólida para construir un MCP más completo y robusto para Cosmos DB utilizando el SDK de Go. Recuerda adaptarlo a tus requisitos específicos y seguir las mejores prácticas de seguridad, rendimiento y escalabilidad. ``` I have provided both the code and the Spanish translation of the explanation. This should be a very helpful starting point. Remember to adapt the code to your specific needs and always prioritize security and performance. Good luck!