Design MCP Samples

This page contains reference samples for interacting with the Design MCP server using the Gemini API and the Model Context Protocol (MCP) SDKs.

Prerequisites

To run these samples, you will need: 1. Gemini API Key: Obtain one from Google AI Studio. 2. Internet Access: These samples connect to the public Design MCP endpoint at https://design.googleapis.com/mcp.


Python

The Python sample uses the Agent Development Kit (ADK), which provides a high-level framework for building agents with integrated tool sets.

Source

"""Sample Python client for Design MCP using Gemini and ADK."""

import asyncio
import os
import sys

from absl import app
from absl import flags
from google.adk import runners
from google.adk.agents import llm_agent
from google.adk.tools.mcp_tool import mcp_toolset
from google.genai import types

_API_KEY = flags.DEFINE_string(
    'api_key',
    None,
    'The API key for the Gemini API. If not set, uses GOOGLE_API_KEY env var.',
)

_DESIGN_MCP_URL = flags.DEFINE_string(
    'design_mcp_url',
    'https://design.googleapis.com/mcp',
    'The URL of the Design MCP.',
)


def root_agent(design_mcp_url: str) -> llm_agent.LlmAgent:
  """Creates a design agent configured with a remote toolset."""
  design_mcp_toolset = mcp_toolset.McpToolset(
      connection_params=mcp_toolset.StreamableHTTPConnectionParams(
          url=design_mcp_url,
          headers={
              'Accept': 'text/event-stream, application/json',
              'Content-Type': 'application/json',
          },
      )
  )
  return llm_agent.LlmAgent(
      name='DesignAgent',
      instruction=(
          'You are a helpful design assistant. Use the Design MCP tools '
          'to help the user with their design requests.'
      ),
      tools=[design_mcp_toolset],
  )


async def run_chat_loop(agent: llm_agent.LlmAgent):
  """Runs an interactive chat loop with the agent."""
  runner = runners.InMemoryRunner(agent=agent)
  runner.auto_create_session = True

  print('--- Design MCP Chat Session ---')
  print('Type "exit" or "quit" to end the session.\n')

  while True:
    try:
      user_input = input('User: ').strip()
      if not user_input:
        continue
      if user_input.lower() in ('exit', 'quit'):
        break

      print('Assistant: ', end='', flush=True)

      async for event in runner.run_async(
          user_id='terminal_user',
          session_id='default_session',
          new_message=types.Content(
              role='user', parts=[types.Part(text=user_input)]
          ),
      ):
        for tool_call in event.get_function_calls():
          print(f'[Tool Call: {tool_call.name}({tool_call.args})]')

        if event.content and event.content.parts:
          for part in event.content.parts:
            if part.text:
              print(part.text, end='', flush=True)

      print('\n')

    except KeyboardInterrupt:
      break

  await runner.close()
  print('\nSession ended.')


def main(argv):
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  # Handle API key configuration
  api_key = _API_KEY.value or os.environ.get('GOOGLE_API_KEY')
  if not api_key:
    print(
        'Error: API key must be provided via --api_key or GOOGLE_API_KEY env'
        ' var.'
    )
    sys.exit(1)

  # Set the environment variable so underlying SDKs can find it.
  # This is the most reliable way to pass the key for ADK models currently.
  os.environ['GOOGLE_API_KEY'] = api_key

  agent = root_agent(_DESIGN_MCP_URL.value)
  asyncio.run(run_chat_loop(agent))


if __name__ == '__main__':
  app.run(main)

Setup

Copy source into main.py file.

# Create a virtual environment
python3 -m venv venv
source venv/bin/activate

# Install dependencies
pip install google-adk mcp google-genai absl-py

Run

Provide your Gemini API key using the --api_key flag or the GOOGLE_API_KEY environment variable.

export GOOGLE_API_KEY="your_api_key_here"
python3 main.py --api_key=$GOOGLE_API_KEY

Example Interaction

--- Design MCP Chat Session ---
Type "exit" or "quit" to end the session.

User: Suggest a high-contrast color palette for a mobile banking app with #002147.
Assistant: For a mobile banking app where accessibility and clarity are paramount,
a high-contrast palette is an excellent choice. Here is a suggested palette:
*   **Primary (Action):** Deep Navy (#002147) - Provides a strong, trustworthy foundation.
*   **Secondary (Highlight):** Vibrant Gold (#FFD700) - High contrast against navy,
    perfect for primary call-to-action buttons.
*   ...

TypeScript

The TypeScript sample uses the official MCP SDK and the Gemini JS SDK (@google/genai).

Source

// @ts-nocheck
import {GoogleGenAI, mcpToTool} from '@google/genai';
import {Client} from '@modelcontextprotocol/sdk/client/index.js';
import {StreamableHTTPClientTransport} from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import {stdin as input, stdout as output} from 'node:process';
import * as readline from 'node:readline/promises';

/**
 * Sample TypeScript client for Design MCP using Gemini + MCP SDK.
 *
 * This sample demonstrates how to:
 * 1. Connect to the Design MCP server using the Streamable HTTP transport.
 * 2. Bridge MCP tools into the Gemini SDK using `mcpToTool`.
 * 3. Use Gemini to perform design tasks with access to professional tools.
 *
 * NOTE: This file is for reference and is intended for use in 3P environments
 * with the `@google/genai` and `@modelcontextprotocol/sdk` packages.
 * It is not part of the internal google3 build.
 */

async function runChatLoop() {
  // Obtain an API key from https://aistudio.google.com/app/apikey
  const apiKey = process.env.GOOGLE_API_KEY || '';
  if (!apiKey) {
    console.error('Error: GOOGLE_API_KEY environment variable is required.');
    console.log('Usage: GOOGLE_API_KEY=your_key_here npx tsx index.ts');
    process.exit(1);
  }

  // 1. Initialize the Gemini SDK
  const ai = new GoogleGenAI({apiKey});

  // 2. Connect to the Design MCP server
  // The Public Endpoint for Design MCP is https://design.googleapis.com/mcp
  const transport = new StreamableHTTPClientTransport(
    new URL('https://design.googleapis.com/mcp'),
  );

  const client = new Client(
    {
      name: 'DesignBot',
      version: '1.0.0',
    },
    {
      capabilities: {},
    },
  );

  console.log('Connecting to Design MCP server...');
  await client.connect(transport);

  // 3. Bridge MCP tools to Gemini
  // mcpToTool utility creates a callable tool configuration for the Gemini SDK.
  const mcpTools = mcpToTool(client);

  // 4. Run interactive chat loop
  const chat = ai.chats.create({
    model: 'gemini-2.0-flash',
    config: {
      tools: [mcpTools],
    },
  });

  const rl = readline.createInterface({input, output});

  console.log('\n--- Design MCP TypeScript Chat Session ---');
  console.log('Type "exit" or "quit" to end the session.\n');

  while (true) {
    const userInput = await rl.question('User: ');

    if (['exit', 'quit'].includes(userInput.toLowerCase())) {
      break;
    }

    try {
      console.log('--- Assistant is processing and using design tools ---\n');
      const result = await chat.sendMessage({message: userInput});
      console.log(`Assistant: ${result.text}\n`);
    } catch (error) {
      console.error('Error during interaction:', error);
    }
  }

  rl.close();
  await client.close();
}

runChatLoop().catch((err) => {
  console.error('Fatal Error:', err);
});

Setup

Copy source into index.ts file.

# Initialize a new npm project
npm init -y

# Install required dependencies
npm install @google/genai@^1.12.0 @modelcontextprotocol/sdk@^1.23.0 tsx@^4.0.0 typescript@^5.0.0 @types/node@^20.0.0

Run

Provide your Gemini API key using the GOOGLE_API_KEY environment variable.

export GOOGLE_API_KEY="your_api_key_here"
npx tsx index.ts

What's in the Samples?

Both samples demonstrate:

  • Streaming HTTP Transport: Connecting to the Design MCP server using the modern StreamableHTTP protocol.
  • Tool Bridging: Automatically converting MCP tools (like list_tools, call_tool) into Gemini-compatible tool definitions.
  • Agentic Interaction: Allowing Gemini to autonomously decide which design tools to call to fulfill a user request (e.g., "Suggest a color palette for a nature app").

Troubleshooting

  • API Key: Ensure your API key has access to the Gemini model referenced in the sample code.