Servidor MCP gerenciado pelo Snowflake

Visão geral

Nota

Snowflake oferece suporte à revisão do protocolo de contexto do modelo 2025-06-18.

Protocolo de contexto do modelo (MCP), é um padrão de código aberto que permite que os agentes de AI interajam de forma segura com aplicativos comerciais e sistemas de dados externos, como bancos de dados e repositórios de conteúdo. o MCP permite que as empresas reduzam os desafios de integração e forneçam resultados rapidamente a partir de modelos. Desde seu lançamento, o MCP tornou-se fundamental para aplicativos de agente, fornecendo um mecanismo consistente e seguro para invocar ferramentas e recuperar dados.

The Snowflake-managed MCP server lets AI agents securely retrieve data from Snowflake accounts without needing to deploy separate infrastructure. You can configure the MCP server to serve Cortex Analyst, Cortex Search, and Cortex Agents as tools, along with custom tools and SQL executions on the standards-based interface. MCP clients discover and invoke these tools, and retrieve data required for the application. With managed MCP servers on Snowflake, you can build scalable enterprise-grade applications while maintaining access and privacy controls. The MCP server on Snowflake provides:

  • Integração padronizada: interface unificada para descoberta e invocação de ferramentas, em conformidade com os padrões em rápida evolução.

  • Autenticação abrangente: serviço OAuth integrado do Snowflake para permitir a autenticação baseada em OAuth para integrações MCP.

  • Governança robusta: controle de acesso baseado em função (RBAC) para servidor MCP e ferramentas para gerenciar a descoberta e a invocação de ferramentas.

Para obter mais informações sobre o ciclo de vida do MCP, consulte Ciclo de vida. Para um exemplo de uma implementação do MCP, consulte o guia de início rápido Introdução ao servidor MCP gerenciado pelo Snowflake.

MCP server security recommendations

Importante

When you configure hostnames for MCP server connections, use hyphens (-) instead of underscores (_). MCP servers have connection issues with hostnames containing underscores.

Using multiple MCP servers without verifying tools and descriptions could lead to vulnerabilities such as tool poisoning or tool shadowing. Snowflake recommends verifying third-party MCP servers before using them. This includes any MCP server from another Snowflake user or account. Verify all tools offered by third-party MCP servers.

We recommend using OAuth as the authentication method. Using hardcoded tokens can lead to token leakage.

When using a Programmatic Access Token (PAT), set it to use the least-privileged role allowed to work with MCP. This will help prevent leaking a secret with access to a highly-privileged role.

Configure proper permissions for the MCP server and tools following the least-privilege principle. Access to the MCP Server does not give access to the tools. Permission needs to be granted for each tool.

Criar uma objeto do servidor MCP

Crie um objeto especificando as ferramentas e outros metadados. Os clientes MCP que se conectam ao servidor, após a autenticação necessária, podem descobrir e invocar essas ferramentas.

  1. Navegue até o banco de dados e esquema desejados para criar o servidor MCP.

  2. Criar o servidor MCP:

    CREATE [ OR REPLACE ] MCP SERVER [ IF NOT EXISTS ] <server_name>
      FROM SPECIFICATION $$
        tools:
          - name: "product-search"
            type: "CORTEX_SEARCH_SERVICE_QUERY"
            identifier: "database1.schema1.Cortex_Search_Service1"
            description: "cortex search service for all products"
            title: "Product Search"
    
          - name: "revenue-semantic-view"
            type: "CORTEX_ANALYST_MESSAGE"
            identifier: "database1.schema1.Semantic_View_1"
            description: "Semantic view for all revenue tables"
            title: "Semantic view for revenue"
      $$
    
    Copy

Atualmente, o Snowflake oferece suporte aos seguintes tipos de ferramentas:

  • CORTEX_SEARCH_SERVICE_QUERY: ferramenta Cortex Search Service

  • CORTEX_ANALYST_MESSAGE: ferramenta Cortex Analyst

  • SYSTEM_EXECUTE_SQL: SQL execution

  • CORTEX_AGENT_RUN: Cortex Agent tool

  • GENERIC: tool for UDFs and stored procedures

The following examples show how to configure different tool types:

Using the Analyst tool, your client can generate text from SQL. Use the following code to specify the tool configuration.

Nota

The Snowflake-managed MCP server only supports using semantic views with Cortex Analyst. It does not support semantic models.

tools:
  - name: "revenue-semantic-view"
    type: "CORTEX_ANALYST_MESSAGE"
    identifier: "database1.schema1.Semantic_View_1"
    description: "Semantic view for all revenue tables"
    title: "Semantic view for revenue"
Copy

Use the following examples to create and configure custom tools using UDFs and stored procedures:

The following examples demonstrate creating UDFs that can be used as custom tools:

-- create a simple udf
CREATE OR REPLACE FUNCTION MULTIPLY_BY_TEN(x FLOAT)
RETURNS FLOAT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.8'
HANDLER = 'multiply_by_ten'
AS
$$
def multiply_by_ten(x: float) -> float:
  return x * 10
$$;

SHOW FUNCTIONS LIKE 'MULTIPLY_BY_TEN';

-- test return json/variant
CREATE OR REPLACE FUNCTION CALCULATE_PRODUCT_AND_SUM(x FLOAT, y FLOAT)
RETURNS VARIANT
LANGUAGE PYTHON
RUNTIME_VERSION = '3.8'
HANDLER = 'calculate_values'
AS
$$
import json

def calculate_values(x: float, y: float) -> dict:
  """
  Calculates the product and sum of two numbers and returns them in a dictionary.
  The dictionary is converted to a VARIANT (JSON) in the SQL return.
  """
  product = x * y
  sum_val = x + y

  return {
      "product": product,
      "sum": sum_val
  }
$$;

-- test return list/array
CREATE OR REPLACE FUNCTION GET_NUMBERS_IN_RANGE(x FLOAT, y FLOAT)
RETURNS ARRAY -- Use ARRAY to explicitly state a list is being returned
LANGUAGE PYTHON
RUNTIME_VERSION = '3.8'
HANDLER = 'get_numbers'
AS
$$
def get_numbers(x: float, y: float) -> list:
  """
  Returns a list of integers between x (exclusive) and y (inclusive).
  Assumes x < y.
  """
  # Ensure x and y are treated as integers for range generation
  start = int(x) + 1
  end = int(y) + 1 # range() is exclusive on the stop value

  # Use a list comprehension to generate the numbers
  # The Python list will be converted to a Snowflake ARRAY.
  return list(range(start, end))
$$;
Copy
  1. Para mostrar servidores MCP, use os seguintes comandos:

    SHOW MCP SERVERS IN DATABASE <database_name>;
    SHOW MCP SERVERS IN SCHEMA <schema_name>;
    SHOW MCP SERVERS IN ACCOUNT;
    
    Copy

    The following shows the output of the command:

    |               created_on               |       name        | database_name | schema_name |    owner     |           comment            |
    ------------------------------------------+-------------------+---------------+-------------+--------------+------------------------------
    | Fri, 23 Jun 1967 07:00:00.123000 +0000 | TEST_MCP_SERVER   | TEST_DATABASE | TEST_SCHEMA | ACCOUNTADMIN | [NULL]                       |
    | Fri, 23 Jun 1967 07:00:00.123000 +0000 | TEST_MCP_SERVER_2 | TEST_DATABASE | TEST_SCHEMA | ACCOUNTADMIN | Test MCP server with comment |
    
  2. Para descrever um servidor MCP, use o seguinte comando:

    DESCRIBE MCP SERVER <server_name>;
    
    Copy

    The following shows the output of the command:

    |      name       | database_name | schema_name |    owner     | comment |     server_spec        |               created_on               |
    ------------------------------------------------------------------------------------------------------+-------------------------------------
    | TEST_MCP_SERVER | TEST_DATABASE | TEST_SCHEMA | ACCOUNTADMIN | [NULL]  | {"version":1,"tools":[{"name":"product-search","identifier":"db.schema.search_service","type":"CORTEX_SEARCH_SERVICE_QUERY"}]} | Fri, 23 Jun 1967 07:00:00.123000 +0000 |
    
  3. Para descartar um servidor MCP, use o seguinte comando:

    DROP MCP SERVER <server_name>;
    
    Copy

Controle de acesso

Você pode usar os seguintes privilégios para gerenciar o acesso ao objeto MCP e as ferramentas subjacentes

Privilégio

Objeto

Descrição

OWNERSHIP

Objeto MCP

Necessário para atualizar a configuração do objeto

MODIFY

Objeto MCP

Fornece atualizar, descartar, descrever, mostrar e usar (tools/list e tools/call) na configuração do objeto

USAGE

Objeto MCP

Necessário para conectar-se ao servidor MCP e ferramentas de descoberta

USAGE

Cortex Search Service

Necessário para invocar a ferramenta Cortex Search no servidor MCP

SELECT

Exibição semântica

Necessário para invocar a ferramenta Cortex Analyst no servidor MCP

USAGE

Cortex Agent

Required to invoke the Cortex Agent as a tool in the MCP server

USAGE

User-defined function (UDF) or stored procedure

Required to invoke the UDF or stored procedure as a tool in the MCP server

Configurar a autenticação OAuth

Configure a autenticação no cliente MCP. O servidor MCP gerenciado pelo Snowflake oferece suporte ao OAuth 2.0, alinhado com a recomendação de autorização no protocolo MCP. O servidor MCP gerenciado pelo Snowflake não oferece suporte ao registro dinâmico de clientes.

  1. Primeiro, crie a integração de segurança. Para mais informações sobre esse comando, consulte CREATE SECURITY INTEGRATION (Snowflake OAuth).

    CREATE [ OR REPLACE ] SECURITY INTEGRATION [IF NOT EXISTS] <integration_name>
      TYPE = OAUTH
      OAUTH_CLIENT = GENERIC
      ENABLED = TRUE
      OAUTH_CLIENT_TYPE = 'CONFIDENTIAL'
      OAUTH_REDIRECT_URI = '<redirect_URI>'
    
    Copy
  2. Em seguida, chame a função de sistema para recuperar seu ID de cliente e chaves para configuração do cliente. O nome da integração diferencia maiúsculas de minúsculas e deve estar em maiúsculas.

    SELECT SYSTEM$SHOW_OAUTH_CLIENT_SECRETS('<integration_name>');
    
    Copy

Interagir com o servidor MCP usando um cliente MCP personalizado

Se você estiver criando um cliente MCP personalizado, as seções a seguir demonstram os pontos de extremidade do Snowflake com os quais seu cliente interage.

Nota

Atualmente, o servidor MCP do Snowflake oferece suporte apenas aos recursos da ferramenta.

Inicialização do servidor MCP

Após a autenticação, inicialize o servidor emitindo chamadas GET e POST para o seguinte ponto de extremidade da API:

POST /api/v2/databases/{database}/schemas/{schema}/mcp-servers/{name}
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "initialize",
        "params": { "protocolVersion": "2025-06-18" }
    }
Copy

O exemplo a seguir mostra a resposta:

{
    "jsonrpc": "2.0", // passthrough from req
    "id": 1, // passthrough from req
    "result": {
        "proto_version": "2025-06-18",
        "capabilities": {
            "tools": {
                "listChanged": false
            }
        },
        "server_info": {
            "name": "<snowflake-mcp-name>",
            "title": "Snowflake Server: <snowflake-mcp-name>",
            "version": "1.0.0"
        }
    }
}
Copy

Descobrir e invocar ferramentas

Os clientes MCP podem descobrir e invocar ferramentas com as solicitações tools/list e tools/call.

Para descobrir ferramentas, emita uma chamada POST como mostrado em Solicitação tools/list:

POST /api/v2/databases/{database}/schemas/{schema}/mcp-servers/{name}
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/list",
        "params": {}
    }
Copy

O exemplo a seguir mostra a resposta:

{
    "jsonrpc": "2.0", // passthrough from req
    "id": 1, // passthrough from req
    "result": {
        "tools": [ // search
            {
                "name":"product-search",
                "description":"Test search tool",
                "inputSchema": {
                    "type": "object",
                    "description": "A search query and additional parameters for search.",
                    "properties": {
                        "query": {
                            "description": "Unstructured text query.  Exactly one of 'query' or 'multi_index_query' must be specified.",
                            "type": "string"
                        },
                        "columns": {
                            "description": "List of columns to return.",
                            "type": "array",
                            "items": {
                                "type": "string"
                            }
                        },
                        "filter": {
                            "description": "Filter query.",
                            "type": "object"
                        },
                        "limit": {
                            "description": "Max number of results to return.",
                            "type": "integer",
                            "default": 10
                        }
                    }
                },
                "outputSchema": {
                    "type": "object",
                    "description": "Search results.",
                    "properties": {
                        "results": {
                            "description": "List of result rows.",
                            "type": "array",
                            "items": {
                                "type": "object",
                                "additionalProperties": true,
                                "description": "Map of column names to values (as bytes)."
                            }
                        },
                    "request_id": {
                        "description": "ID of the request.",
                        "type": "string"
                    }
                },
                "required": ["results", "request_id"]
            }
          },
          { // analyst
              "name":"revenue-semantic-view",
              "description":"Test tool",
              "inputSchema": {
                  "type": "object",
                  "description": "A message and additional parameters for Cortex Analyst.",
                  "properties": {
                      "message": {
                          "description": "The user’s question.",
                          "type": "string"
                      }
                  }
              }
          }
        ]
    }
}
Copy

Para invocar uma ferramenta, emita uma chamada POST como mostrado em Solicitação tools/call.

For the Analyst tool, your client passes messages in the request. The SQL statement is listed in the output. You must pass the name of the tool that you’re invoking in the request in the name parameter.

POST /api/v2/databases/<database>/schemas/<schema>/mcp-servers/<name>
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "test-analyst",
            "arguments": {
                "message ": "text"
            }
        }
    }
Copy

O exemplo a seguir mostra a resposta:

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "content": [
            {
                "type": "text",
                "text": "string"
            }
        ]
    }
}
Copy

Para solicitações de ferramentas de pesquisa, seu cliente pode passar a consulta e os seguintes argumentos opcionais:

  • columns

  • filter

  • limit

The search results and request ID are returned in the output. You must pass the name of the tool that you’re invoking in the request as the name parameter.

POST /api/v2/databases/{database}/schemas/{schema}/mcp-servers/{name}
    {
        "jsonrpc": "2.0",
        "id": 1,
        "method": "tools/call",
        "params": {
            "name": "product-search",
            "arguments": {
                "query": "Hotels in NYC",
                "columns": array of strings,
                "filter": json,
                "limit": int
            }
        }
  }
Copy

O exemplo a seguir mostra a resposta:

{
    "jsonrpc": "2.0",
    "id": 1,
    "result": {
        "results": {}
    }
}
Copy

Limitações

O servidor MCP gerenciado pelo Snowflake não oferece suporte aos seguintes constructos no protocolo MCP: recursos, prompts, raízes, notificações, negociações de versão, fases do ciclo de vida e amostragem.

Somente respostas sem streaming são compatíveis.