Salta al contenuto principale

25 - MCP in Copilot e Custom Instructions Avanzate

25 - MCP in Copilot e Custom Instructions Avanzate Da marzo 2025, quando GitHub ha introdotto il Model Context Protocol (MCP) in preview negli editor...

Cosa ne pensi di questo articolo?

25 - MCP in Copilot e Custom Instructions Avanzate
GitHub CopilotFoto:olia danilevichPexels

In Breve

25 - MCP in Copilot e Custom Instructions Avanzate Da marzo 2025, quando GitHub ha introdotto il Model Context Protocol (MCP) in preview negli editor...

25 - MCP in Copilot e Custom Instructions Avanzate

Da marzo 2025, quando GitHub ha introdotto il Model Context Protocol (MCP) in preview negli editor dotati di Copilot, il modo in cui gli sviluppatori estendono e personalizzano il loro assistente AI è radicalmente cambiato. A luglio 2025, MCP è diventato generalmente disponibile (GA) in VS Code 1.102. A marzo 2026, lo stesso protocollo è ora condiviso tra VS Code e la Copilot CLI, con supporto per sandbox limitati su macOS e Linux.

Combinato con la nuova gerarchia di custom instructions e i file .prompt.md on-demand, MCP abilita workflow potentissimi: integrare database personali direttamente in Copilot, connettere servizi aziendali, creare agenti AI specializzati per specifici task e costruire ecosistemi di strumenti che moltiplicano la produttività del team.

Cosa Imparerai

  • Configurare MCP server in mcp.json (workspace e user settings)
  • Usare server MCP pubblici (filesystem, GitHub, PostgreSQL, Slack)
  • Scrivere custom instructions efficaci a livello repo
  • Creare template on-demand con .prompt.md files
  • Definire custom agents in .github/agents/
  • Implementare sandbox MCP per isolamento di sicurezza
  • Configurare MCP per ambienti produttivi e team
  • Migrare da GitHub App Extensions deprecate verso MCP

Panoramica della Serie Completa

#ArticoloFocus
1Claude come Partner TecnicoSetup e primi passi
2Contesto e Setup del ProgettoCLAUDE.md e configurazione
3Ideazione e RequisitiMVP e user personas
4Architettura Backend e FrontendSpring Boot e Angular
5Struttura del CodiceOrganizzazione e convenzioni
6Prompt Engineering AvanzatoTecniche avanzate
7Testing e qualitàStrategie e generazione test
8Documentazione ProfessionaleREADME, API, ADR
9Deploy e DevOpsDocker, CI/CD, monitoring
10Evoluzione e ManutenzioneRefactoring e scalabilità
11Integrazione Progetto RealeClaude Code in produzione
12Claude Code CLIComandi e configurazione
13Agent Skillscapacità modulari
14Subagenti SpecializzatiAgenti con ruoli specifici
15Hooks e AutomazioneEvent-driven workflows
16Ralph Wiggum MethodSviluppo guidato da test
17BMAD MethodGestione progetti strutturata
18Orchestrazione Multi-AgentePipeline di agenti
19Collaborative WorkTeam e pair programming AI
20Sicurezza e Best PracticeHardening e compliance
21Monitoring e ObservabilityMetriche e debugging
22GitHub Copilot ProFunzionalità avanzate
23Prompt CachingOttimizzazione costi e latenza
24Copilot WorkspaceSviluppo full-stack collaborativo
25MCP e Custom Instructions (sei qui)Estensioni e personalizzazione

1. Dal Paradigma delle Extensions al Model Context Protocol

Prima di marzo 2025, il modo di estendere GitHub Copilot era limitato e frammentato:

  • GitHub App Extensions (deprecate): sviluppatori dovevano registrare app OAuth separate, compilare manifest JSON, gestire token, e spesso l'integrazione era lenta e soggetta a ratifica.
  • Editor-specific integrations: VS Code Copilot funzionava diversamente da JetBrains Copilot, senza uno standard condiviso.
  • Assenza di tool standardizzati: Non c'era modo uniforme di dire a Copilot "qui ho un database", "usa questo API endpoint", "leggi da questo filesystem".

Il Model Context Protocol (MCP) è lo standard completamente nuovo che cambia il paradigma. Originariamente creato da Anthropic come protocollo aperto per collegare LLM a fonti di dati e tool, GitHub lo ha adottato come standard per Copilot. Questo significa:

Vantaggi del Paradigma MCP

  • Standard condiviso: VS Code, JetBrains, Copilot CLI, persino client custom usano lo stesso protocollo
  • Decoupling: i tool MCP sono indipendenti dall'editor - uno stesso server MCP funziona ovunque
  • Composizione: connetti più MCP server nello stesso workspace e il modello li usa tutti come toolbox unificato
  • Sandbox: (a marzo 2026) supporto per MCP server in ambienti isolati con accesso file/network limitato
  • Open source: hundreds di server MCP già implementati - database, filesystem, GitHub, Slack, Sentry, MongoDB, ecc.

2. MCP in VS Code 1.99 (Marzo 2025) - Agent Mode Preview

A marzo 2025, VS Code 1.99 ha introdotto la Agent Mode preview per Copilot. In questa modalità, Copilot non è solo un autocomplete o un chatbot - diventa un agente che può usare tool per completare i tuoi task.

.vscode/settings.json - Abilitare Agent Mode in preview
{
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "copilot.experimental.agentMode": true,
  "copilot.experimental.contextWindow": "extended"
}

Con Agent Mode abilitato, Copilot ha accesso ai tool registrati nel workspace. Per registrare i tool, crei un file mcp.json nella root del progetto oppure in ~/.vscode/extensions/copilot/mcp.json a livello user.

.vscode/mcp.json - Registrazione server MCP in preview (marzo 2025)
{
  "mcpServers": {
    "filesystem": {
      "command": "node",
      "args": ["mcp-server-filesystem/index.js"],
      "disabled": false,
      "alwaysAllow": ["read", "list", "create"]
    },
    "github": {
      "command": "node",
      "args": ["mcp-server-github/index.js"],
      "env": {
        "GITHUB_TOKEN": "$GITHUB_TOKEN"
      },
      "disabled": false
    }
  }
}

Nell'implementazione preview, Copilot interroga ogni MCP server registrato per elencare i tool disponibili e (quando richiesto) li usa nel suo reasoning. Ad esempio:

Esempio: Copilot usa tool MCP in Agent Mode (preview)
Prompt: "Rileggi tutti i file TypeScript in src/ e segnala errori di type safety"

Copilot reasoning:
1. Utente chiede di leggere file TypeScript
2. Disponibili tool: [filesystem.read, filesystem.list, ...]
3. Esecuzione: filesystem.list("src/", pattern="*.ts") → 47 file
4. Per ogni file: filesystem.read("src/...") → analizza con TypeScript compiler
5. Segnala errori trovati

Output: "Trovati 3 type errors in src/components/ ..."

3. MCP Generalmente Disponibile in VS Code 1.102 (14 Luglio 2025)

Il 14 luglio 2025, GitHub ha reso MCP generally available (GA) in VS Code 1.102. Le novità della release GA includono:

Novità della Release GA (luglio 2025)

  • Stabilità e performance: ottimizzazione delle richieste tool, caching dei risultati
  • OAuth per MCP remote: server MCP su host remoti (es. cloud) autenticati via OAuth
  • Personal Access Token (PAT): autenticazione semplificata con PAT GitHub per server MCP
  • Error handling robusto: timeout, retry policy, fallback su tool failure
  • Tool categorization: i tool MCP sono ora categorizzati (read, write, execute) per UI migliore
  • Configuration validation: VS Code valida la configurazione mcp.json al boot e segnala errori
.vscode/mcp.json - Configurazione completa (GA, luglio 2025)
{
  "mcpServers": {
    "filesystem": {
      "command": "node",
      "args": ["path/to/mcp-server-filesystem.js"],
      "cwd": "${workspaceFolder}",
      "env": {
        "NODE_ENV": "production"
      },
      "disabled": false
    },
    "github": {
      "command": "node",
      "args": ["path/to/mcp-server-github.js"],
      "env": {
        "GITHUB_TOKEN": "${env:GITHUB_TOKEN}",
        "GITHUB_OWNER": "fedcal",
        "GITHUB_REPO": "PortfolioPersonaleAngular"
      },
      "disabled": false
    },
    "postgres": {
      "command": "node",
      "args": ["path/to/mcp-server-postgres.js"],
      "env": {
        "DATABASE_URL": "${env:DATABASE_URL}",
        "DB_USER": "${env:DB_USER}",
        "DB_PASSWORD": "${env:DB_PASSWORD}"
      },
      "disabled": false
    },
    "slack": {
      "command": "node",
      "args": ["path/to/mcp-server-slack.js"],
      "env": {
        "SLACK_BOT_TOKEN": "${env:SLACK_BOT_TOKEN}"
      },
      "disabled": false
    },
    "sentry": {
      "command": "python3",
      "args": ["-m", "mcp_server_sentry"],
      "env": {
        "SENTRY_AUTH_TOKEN": "${env:SENTRY_AUTH_TOKEN}",
        "SENTRY_ORG": "myorg",
        "SENTRY_PROJECT": "myproject"
      },
      "disabled": false
    }
  },
  "env": {
    "GITHUB_TOKEN": "ghp_xxxxx",
    "DATABASE_URL": "postgresql://user:pass@localhost:5432/mydb",
    "SLACK_BOT_TOKEN": "xoxb-xxxxx"
  }
}

Questa configurazione connette 5 server MCP contemporaneamente, permettendo a Copilot di:

  • filesystem: leggere, scrivere, listare file nel workspace
  • github: query issue, PR, commit, workflows nel repository
  • postgres: interrogare il database direttamente (SELECT, tabelle schema, analisi dati)
  • slack: inviare messaggi, leggere cronologie, gestire thread
  • sentry: query errori in produzione, analizzare breadcrumb, ottenere stack trace

4. MCP Condiviso tra VS Code e Copilot CLI (Marzo 2026)

A marzo 2026, GitHub ha unificato il supporto MCP tra VS Code e la Copilot CLI. Questo significa che puoi configurare i tuoi server MCP una volta e usarli ovunque: nell'editor, dal terminale con la CLI, e anche in script di automazione.

Configurazione MCP a livello user (marzo 2026)
~/.copilot/mcp.json  - Configurazione globale (tutti i progetti)

~/.copilot/mcp.json:
{
  "mcpServers": {
    "github": {
      "command": "node",
      "args": ["/usr/local/lib/mcp-server-github/index.js"],
      "env": {
        "GITHUB_TOKEN": "${env:GITHUB_TOKEN}"
      }
    },
    "filesystem": {
      "command": "node",
      "args": ["/usr/local/lib/mcp-server-filesystem/index.js"]
    }
  }
}

Con questa configurazione globale, sei casi d'uso diventano possibili:

Casi d'Uso Unificati (marzo 2026)

ContestoUsoTool MCP disponibili
VS Code editor Copilot: Inline Chat (Cmd+I) github + filesystem (global + workspace)
VS Code sidebar chat Cmd+L per aprire Copilot Chat github + filesystem (global + workspace)
Terminal CLI copilot --model claude-opus-4 --with-tools github,filesystem "Crea PR con..." github + filesystem (global config)
Script di automazione copilot --print "Genera report..." --output json --tools postgres postgres (global config)
GitHub Actions github-action-copilot ufficiale con MCP support github + custom (nella Action)

Questo paradigma abolisce la distinzione artificiosa tra "sviluppo nell'editor" e "automazione CLI". Copilot diventa un assistente coerente ovunque tu sia.

5. Sandbox MCP Server - Isolamento di Sicurezza (Marzo 2026)

A marzo 2026, VS Code ha introdotto il supporto per MCP server in sandbox su macOS e Linux. Un server MCP in sandbox ha accesso limitato al filesystem e alla rete - questo è critico quando usi MCP server di terze parti e vuoi proteggere i tuoi dati sensibili.

.vscode/mcp.json - Server MCP con sandbox abilitato (marzo 2026)
{
  "mcpServers": {
    "untrusted-thirdparty-tool": {
      "command": "node",
      "args": ["path/to/unknown-mcp-server.js"],
      "sandbox": {
        "enabled": true,
        "allowedPaths": [
          "${workspaceFolder}/src",
          "${workspaceFolder}/docs"
        ],
        "blockedPaths": [
          "${workspaceFolder}/.env",
          "${workspaceFolder}/.env.prod",
          "${HOME}/.ssh",
          "${HOME}/.aws"
        ],
        "allowedNetworkDomains": ["api.example.com"],
        "blockedNetworkDomains": ["*"]
      },
      "disabled": false
    },
    "trusted-postgres": {
      "command": "node",
      "args": ["mcp-server-postgres"],
      "sandbox": {
        "enabled": false
      }
    }
  }
}

Con questa configurazione:

  • untrusted-thirdparty-tool: ha accesso SOLO a src/ e docs/, non può leggere .env o ~/.ssh, e non può connettersi a nessun dominio se non api.example.com
  • trusted-postgres: no sandbox (configurazione di default), accesso completo

Sandbox Availabilità e Limitazioni

Disponibilità (marzo 2026): sandbox è supportato su macOS 12+ e Linux (tramite seccomp + namespaces). Su Windows, sandbox non è ancora disponibile (limitazione di WSL2).

Meccanismo: su macOS usa App Sandbox (entitlements), su Linux usa seccomp filter + kernel namespaces. Le prestazioni hanno un overhead di ~5-10% per sistema file e rete.

6. Fine delle GitHub App Extensions (10 Novembre 2025)

Il 10 novembre 2025, GitHub ha deprecato ufficialmente il supporto per GitHub App-based Copilot Extensions. Questo significa che qualsiasi extension sviluppato con il vecchio paradigma OAuth GitHub App smette di funzionare il 1 gennaio 2026.

Gli sviluppatori di extension (Sentry, Docker, MongoDB, Stripe, ecc.) hanno migrato verso MCP durante 2025. Il percorso di migrazione da GitHub App Extension a MCP server è straightforward:

Migrazione: GitHub App Extension → MCP Server
== PRIMA (GitHub App Extension - DEPRECATA) ==
❌ github-app/manifest.json (OAuth setup complesso)
❌ Registrazione manuale in GitHub Marketplace
❌ Ogni editor supportava il protocollo diversamente
❌ Nessun sandbox, accesso non ristretto

== DOPO (MCP Server - NUOVO STANDARD) ==
✅ mcp.json con server command + args
✅ Zero registrazione GitHub, basta installare il package npm
✅ Funziona ovunque: VS Code, JetBrains, CLI, custom client
✅ Sandbox support on demand

== ESEMPIO: Migrazione Sentry Extension ==

Prima (GitHub App):
1. Registra GitHub App OAuth
2. Installa extension da Marketplace
3. Extension autentica con GitHub
4. Sentry API calls via OAuth token

Dopo (MCP):
1. npm install mcp-server-sentry
2. Aggiungi a .vscode/mcp.json o ~/.copilot/mcp.json:
   {
     "sentry": {
       "command": "node",
       "args": ["-m", "mcp_server_sentry"],
       "env": { "SENTRY_AUTH_TOKEN": "${env:SENTRY_AUTH_TOKEN}" }
     }
   }
3. Usa in Copilot Chat: "Mostra i 10 errori più recenti da Sentry"
4. MCP server chiama Sentry API con token

La maggior parte delle extension "note" ha già implementato un MCP server equivalente:

MCP Server ufficiali di terze parti (estratto, aprile 2026)

ServizioMCP ServerFunzionalità principale
Sentry mcp-server-sentry (ufficiale) Query errori, analisi breadcrumb, release management
Docker mcp-server-docker (ufficiale) Gestione container, immagini, volumes
MongoDB mcp-server-mongodb (ufficiale) Query database, aggregation, schema introspection
Stripe mcp-server-stripe (ufficiale) Query transazioni, subscription, customer management
AWS mcp-server-aws (ufficiale) CloudFormation, EC2, S3, DynamoDB
Slack mcp-server-slack (ufficiale) Messaggi, channel, user, workflow automation
GitHub mcp-server-github (ufficiale) Issue, PR, commit, workflows, releases

7. Gerarchia Custom Instructions - Tre Tier

Oltre ai tool MCP, Copilot supporta custom instructions che specificano come il modello deve comportarsi nel tuo contesto specifico. Ci sono tre tier di configurazione, con precedenza decrescente:

Tier di Custom Instructions

TierFileScopePrecedenzaAuto-attach
1. Prompt Files .prompt.md (in qualsiasi dir) On-demand, triggato da comandi Massima (esplicita) No, invocato esplicitamente
2. Repo Instructions .github/copilot-instructions.md Tutti gli sviluppatori del repo Alta (automatica) Sì, su ogni chat inline
3. Workspace Settings .vscode/settings.json (config key) Dev locale + CI/CD environment Media Sì, all'avvio
4. User Global ~/.copilot/instructions.md Tutti i progetti dell'utente Bassa (default) Sì, fallback globale

Tier 1: Repo-scoped Instructions (.github/copilot-instructions.md)

Il file .github/copilot-instructions.md contiene regole, convenzioni e linee guida che Copilot deve seguire automaticamente in ogni chat all'interno del repository.

.github/copilot-instructions.md - Linee guida repo Spring Boot
# Copilot Instructions for PortfolioPersonaleAngular Backend

## Architecture
- Follow Clean Architecture 4-layer pattern (domain, application, infrastructure, presentation)
- Domain layer: ZERO framework dependencies
- Application layer: orchestrate domain + infrastructure, implement use cases
- Infrastructure layer: implement domain ports, handle external integrations
- Presentation layer: REST controllers, error handling, DTOs

## Code Style
- Language: Java 21, Spring Boot 3.4
- Pattern: Records for DTOs (immutability first)
- Validation: use @Validated and custom validators
- Exception Handling: create domain exceptions, not generic RuntimeException

## Testing
- Framework: JUnit 5 + Mockito + Testcontainers
- Coverage: target 80%+ on business logic
- Test naming: method_givenContext_thenExpectation
- Integration tests use Testcontainers for PostgreSQL + Redis

## Database
- ORM: Spring Data JPA + Hibernate 6
- Migrations: Flyway (V001..VnNN pattern)
- Transactions: use @Transactional only on service layer
- Caching: @Cacheable on read-heavy queries

## API Design
- REST endpoints: /api/v1/resource
- DTOs: request/response separation
- Pagination: use Spring Data Page
- Error responses: standardized ErrorResponse envelope

## Security
- Authentication: JWT proprietario (HS256)
- Role hierarchy: GUEST < USER < PRO < MODERATOR < ADMIN < SUPER_ADMIN
- Rate limiting: Bucket4j via Redis
- CORS: whitelist federicocalo.dev + localhost dev

Tier 2: On-demand .prompt.md Files

I file .prompt.md sono template on-demand che puoi invocare esplicitamente con comandi. Ogni file diventa un "prompt salvato" che Copilot carica quando lo richiedi.

.prompt.md example - /generate-rest-controller
> getAll(
    @ParameterObject @PageableDefault(size = 20, sort = "id", direction = Sort.Direction.DESC) Pageable pageable
  ) {
    return ResponseEntity.ok(service.findAll(pageable));
  }

  @GetMapping("/{id}")
  public ResponseEntity<{ResourceName}Response> getById(@PathVariable Long id) {
    return ResponseEntity.ok(service.findById(id));
  }

  @PostMapping
  @ResponseStatus(HttpStatus.CREATED)
  public ResponseEntity<{ResourceName}Response> create(@Valid @RequestBody {ResourceName}Request request) {
    return ResponseEntity.status(HttpStatus.CREATED).body(service.create(request));
  }

  @PutMapping("/{id}")
  public ResponseEntity<{ResourceName}Response> update(
    @PathVariable Long id,
    @Valid @RequestBody {ResourceName}Request request
  ) {
    return ResponseEntity.ok(service.update(id, request));
  }

  @DeleteMapping("/{id}")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void delete(@PathVariable Long id) {
    service.delete(id);
  }
}
\`\`\`

## Usage in Copilot
Type in chat: `@.prompt /generate-rest-controller ResourceName=User`

Copilot will:
1. Generate the controller class
2. Generate request/response DTOs
3. Create the service interface
4. Add unit test class

Per usare questo template, scrivi in Copilot Chat:

Uso del .prompt.md in Copilot Chat
Copilot Chat prompt:
> @.prompt /generate-rest-controller ResourceName=Product Category=ProductCategory

Copilot interpretation:
1. Carica template .prompt.md "generate-rest-controller"
2. Sostituisce variabili: {ResourceName} → Product, {ResourceName}Response → ProductResponse
3. Executes template logic: genera controller, DTOs, service, test
4. Output: 4 file Java creati con codice completo

Tier 3: Workspace Settings in .vscode/settings.json

.vscode/settings.json - Copilot settings per workspace
{
  "copilot.codeReviewAuto": true,
  "copilot.contextWindow": "extended",
  "copilot.customInstructions": {
    "languages": ["java", "typescript", "markdown"],
    "tone": "concise and technical",
    "targetAudience": "senior developers"
  },
  "copilot.disabledInComments": false,
  "copilot.inlineCompletions.enabled": true,
  "copilot.chat.runCommandWithSelection": true
}

8. Custom Agents in .github/agents/

Oltre alle istruzioni, puoi definire custom agents che sono persona complete con prompt, tool restriction e specializzazione. Ogni agent è un file YAML in .github/agents/.

.github/agents/security-reviewer.yml - Security expert agent
name: security-reviewer
displayName: Security Reviewer
description: Analyzes code for security vulnerabilities and compliance issues

systemPrompt: |
  You are a security expert reviewing code for vulnerabilities.

  Your analysis focuses on:
  1. OWASP Top 10 vulnerabilities (SQL injection, XSS, CSRF, etc.)
  2. Authentication & authorization flaws
  3. Sensitive data exposure (credentials, PII)
  4. Insecure cryptography
  5. Access control misconfigurations

  Output format:
  - Severity: CRITICAL / HIGH / MEDIUM / LOW
  - CWE reference: link to CWE database
  - Vulnerability description
  - Proof of concept (if applicable)
  - Remediation steps

allowedTools:
  - filesystem:read    # Can read code files
  - filesystem:list    # Can list directories
  - github:searchCode  # Can search code in repo
  - github:getPullRequest # Can analyze PR diffs

restrictedTools:
  - filesystem:write   # Cannot modify code
  - filesystem:delete  # Cannot delete files
  - github:approve     # Cannot approve PRs (advisory only)

context:
  - "src/**/*.java"
  - "src/**/*.ts"
  - "backend/src/**/*"
  - "frontend/src/**/*"

ignorePatterns:
  - "node_modules/**"
  - "dist/**"
  - "*.lock"
  - "*.log"

Per usare un agent personalizzato, invochi il nome in Copilot Chat:

Invocazione di agent personalizzato
Copilot Chat:
> @security-reviewer analyze src/main/java/dev/federicocalo/portfolio/presentation/controller/AuthController.java

Copilot behavior:
1. Carica agent "security-reviewer" da .github/agents/security-reviewer.yml
2. Applica systemPrompt
3. Usa SOLO tool in allowedTools (filesystem:read, github, ecc.)
4. Blocca tool in restrictedTools (filesystem:write)
5. Limita context a "src/**/*.java"
6. Output: security report dettagliato

Sample output:
---
🔴 CRITICAL: SQL Injection in AuthController.java:142
CWE-89: Improper Neutralization of Special Elements used in an SQL Command

Vulnerability:
String query = "SELECT * FROM users WHERE email = '" + email + "'";
This concatenates user input directly into SQL query.

Remediation:
Use parameterized queries (PreparedStatement):
String query = "SELECT * FROM users WHERE email = ?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, email);

---
🟡 MEDIUM: Missing CSRF token validation in POST endpoints
CWE-352: Cross-Site Request Forgery (CSRF)

Recommendation:
Enable @EnableWebSecurity with .csrf(csrf -> csrf.disable()) removed.
Use @GetMapping for idempotent operations, @PostMapping for state changes.
---

9. MCP Server Pubblici - Guida Pratica

Ci sono centinaia di server MCP open-source pronti all'uso. Ecco quelli più utili per sviluppatori.

Server MCP essenziali (aprile 2026)

ServerPackageCaso d'usoAutenticazione
Filesystem mcp-server-filesystem Leggere, listare, creare file nel workspace None (sandbox per sicurezza)
GitHub mcp-server-github Issue, PR, commit, workflows GitHub PAT o OAuth
PostgreSQL mcp-server-postgres Query database, schema introspection DATABASE_URL env var
Slack mcp-server-slack Messaggi, channel, thread, user lookup SLACK_BOT_TOKEN
MongoDB mcp-server-mongodb Query, aggregation, index management MONGODB_URL env var
Sentry mcp-server-sentry Errori produzione, breadcrumb, releases SENTRY_AUTH_TOKEN
Docker mcp-server-docker Gestione container, immagini, logs Docker socket access
AWS mcp-server-aws CloudFormation, EC2, S3, Lambda, DynamoDB AWS_ACCESS_KEY_ID + SECRET
Installazione server MCP utili (npm + Python)
#!/bin/bash
# Installa server MCP globali in ~/.local/bin/mcp/

mkdir -p ~/.local/bin/mcp
cd ~/.local/bin/mcp

# 1. Node.js-based servers
npm install -g mcp-server-filesystem
npm install -g mcp-server-github
npm install -g mcp-server-postgres
npm install -g mcp-server-slack
npm install -g mcp-server-mongodb
npm install -g mcp-server-docker
npm install -g mcp-server-aws

# 2. Python-based servers (optional)
pip install mcp-server-sentry

# Verifica installazione
which mcp-server-filesystem
which mcp-server-github
which mcp-server-postgres

10. Implementare Custom MCP Server

Per integrare un sistema personale (es. CRM aziendale, API proprietaria, database custom), puoi scrivere il tuo MCP server in poche ore. Ecco un quickstart in Python.

mcp_server_crm.py - Custom MCP server per CRM
#!/usr/bin/env python3
import json
import asyncio
from typing import Any
from mcp.server import Server
from mcp.types import Tool, TextContent, ToolResult

# Custom CRM API client
class CRMClient:
    def __init__(self, api_key: str, base_url: str = "https://api.mycrm.com"):
        self.api_key = api_key
        self.base_url = base_url

    async def search_customers(self, query: str) -> list[dict]:
        """Search customers by name, email, or phone"""
        # Mock implementation (replace with real API calls)
        return [
            {"id": "cust_123", "name": "Acme Corp", "email": "contact@acme.com"},
            {"id": "cust_456", "name": "TechCorp Ltd", "email": "sales@techcorp.com"}
        ]

    async def get_customer_history(self, customer_id: str) -> dict:
        """Get order history and interactions"""
        return {
            "customer_id": customer_id,
            "orders": [{"id": "ord_001", "date": "2024-01-15", "amount": 2500}],
            "interactions": [
                {"type": "email", "date": "2024-04-20", "subject": "Renewal discussion"}
            ]
        }

    async def create_opportunity(self, customer_id: str, deal_value: float, description: str) -> dict:
        """Create new sales opportunity"""
        return {
            "opp_id": "opp_789",
            "customer_id": customer_id,
            "deal_value": deal_value,
            "description": description,
            "status": "open"
        }

# Initialize MCP server
mcp = Server("crm-server")
crm = CRMClient(api_key="$CRMAPIKEY")  # Load from env

# Register tools
@mcp.tool()
async def search_customers(query: str) -> ToolResult:
    """Search for customers in the CRM by name, email, or phone number"""
    results = await crm.search_customers(query)
    return ToolResult(
        content=[TextContent(type="text", text=json.dumps(results, indent=2))],
        is_error=False
    )

@mcp.tool()
async def get_customer_history(customer_id: str) -> ToolResult:
    """Get complete customer history: orders, interactions, notes"""
    history = await crm.get_customer_history(customer_id)
    return ToolResult(
        content=[TextContent(type="text", text=json.dumps(history, indent=2))],
        is_error=False
    )

@mcp.tool()
async def create_opportunity(customer_id: str, deal_value: float, description: str) -> ToolResult:
    """Create a new sales opportunity for a customer"""
    opp = await crm.create_opportunity(customer_id, deal_value, description)
    return ToolResult(
        content=[TextContent(type="text", text=json.dumps(opp, indent=2))],
        is_error=False
    )

if __name__ == "__main__":
    mcp.run()
Registrazione del custom MCP server in .vscode/mcp.json
{
  "mcpServers": {
    "crm": {
      "command": "python3",
      "args": ["/path/to/mcp_server_crm.py"],
      "env": {
        "CRMAPIKEY": "${env:CRM_API_KEY}",
        "CRM_BASE_URL": "https://api.mycompany.crm"
      },
      "disabled": false
    }
  }
}

Ora puoi usare il tuo MCP server personalizzato in Copilot Chat:

Uso del custom CRM MCP server
Copilot Chat:
> @mcp-crm Cerca clienti "Acme" e mostra loro cronologia ordini

Copilot behavior:
1. Invoca tool search_customers("Acme")
2. Riceve [cust_123, cust_456]
3. Invoca get_customer_history("cust_123")
4. Riceve order + interaction history
5. Formatta risposta

Output:
---
Ho trovato 2 clienti Acme:

1. **Acme Corp** (cust_123)
   Email: contact@acme.com
   Ordini recenti:
   - Ord_001: 25 gennaio 2024 - €2.500
   Ultime interazioni:
   - Email: 20 aprile 2024 - "Renewal discussion"

2. **TechCorp Ltd** (cust_456)
   ...
---

11. Sicurezza MCP - Design Flaw (Aprile 2026) e Mitigazioni

Ad aprile 2026, un rapporto di sicurezza ha identificato un design flaw critico nel protocollo MCP stesso: molti server MCP in uso (~200K su GitHub) non validano correttamente i comandi remoti. Questo permette a un agente AI "compromesso" di eseguire azioni non intese.

CVE-Equivalent Design Issue (Aprile 2026)

Problema: Un server MCP riceve richieste tool da Copilot, ma molti server non validano se la richiesta è stata inviata da Copilot ufficiale o da un client malevolo.

Impatto: Se un attaccante compromette il client locale Copilot (es. via estensione malevola), potrebbe comandare server MCP di terze parti senza autorizzazione.

Mitigation (implementato in v2.5+): - MCP server richiedono ora authentication handshake (JWT) - Sandbox filesystem + network limits (vedi sezione 5) - Allowlist di tool disponibili per ogni client

Configurazione MCP-sicura con limitazioni aggressive
{
  "mcpServers": {
    "postgres-prod": {
      "command": "node",
      "args": ["/usr/local/lib/mcp-server-postgres-secure.js"],
      "env": {
        "DATABASE_URL": "${env:DATABASE_URL}",
        "DB_USER": "${env:DB_USER}",
        "DB_PASSWORD": "${env:DB_PASSWORD}",
        "ALLOWED_TABLES": "users,orders,payments",
        "ALLOW_WRITES": "false",
        "ALLOW_DELETES": "false",
        "MAX_ROWS_PER_QUERY": "1000"
      },
      "sandbox": {
        "enabled": true,
        "allowedNetworkDomains": ["database.internal.mycompany.com"],
        "blockedNetworkDomains": ["*"]
      }
    },
    "untrusted-third-party": {
      "command": "node",
      "args": ["some-unknown-mcp-server"],
      "sandbox": {
        "enabled": true,
        "allowedPaths": ["${workspaceFolder}/public"],
        "blockedPaths": ["${workspaceFolder}/.env*", "${HOME}/.ssh"]
      }
    }
  }
}

Best Practice di Sicurezza MCP

  • Sandbox per terze parti: Qualsiasi server MCP non ufficiale deve girare in sandbox
  • Read-only per default: Abilita write/delete solo quando necessario
  • Whitelist dominio rete: Limita connessioni a host noti
  • Audit log: Registra tutte le invocazioni tool MCP (opzionale in settings)
  • Rotate secrets: API key, DB password, token richiesti per server MCP vanno rotati mensili
  • Minimal permissions: Usa account DB con grant SELECT only, no ALTER/DROP

Conclusione

Il Model Context Protocol rappresenta un cambio fondamentale nel modo in cui gli LLM accedono al contesto e usano tool. Combinato con custom instructions e agent specializzati, MCP trasforma Copilot da autocomplete intelligente a assistente full-stack che conosce il tuo codebase, la tua infrastruttura, i tuoi database, e i tuoi team tools.

Punti Chiave

  • MCP è lo standard: VS Code, JetBrains, Copilot CLI usano lo stesso protocollo
  • Configurazione una volta: MCP server in ~/.copilot/mcp.json disponibili ovunque
  • Hundreds di server pubblici: PostgreSQL, GitHub, Slack, Docker, Sentry, AWS, MongoDB
  • Custom server in poche ore: Python o Node.js, registrazione semplice
  • Custom instructions hierarchy: Repo-scoped + on-demand .prompt.md + workspace settings
  • Custom agents: Persona specializzate con tool restriction e systemPrompt
  • Sandbox per sicurezza: Isolamento filesystem + network per server non affidabili
  • Migrazione da GitHub App Extensions: completata entro novembre 2025

Nel prossimo articolo esploreremo la sicurezza avanzata di Copilot: JWT authentication proprietaria, audit log, compliance GDPR, e best practice per ambienti enterprise. Scopriremo come Copilot si integra con policy aziendali di hardening.

Prova Questi Strumenti

Strumenti gratuiti correlati a questo argomento.

Commenti

Caricamento commenti...

Accedi per commentare

Discuti questo articolo nella community

Unisciti al gruppo Telegram per discutere con altri sviluppatori, fare domande e condividere le tue esperienze.

Ti è piaciuto questo articolo?

Esplora altri contenuti sul blog o scopri i miei progetti