This introduction lab provides a comprehensive overview of building Model Context Protocol (MCP) servers with database integration.
You'll understand the business case, technical architecture, and real-world applications through the Zava Retail analytics use case at https://github.com/microsoft/MCP-Server-and-PostgreSQL-Sample-Retail.
Model Context Protocol (MCP) enables AI assistants to securely access and interact with external data sources in real-time. When combined with database integration, MCP unlocks powerful capabilities for data-driven AI applications.
This learning path teaches you to build production-ready MCP servers that connect AI assistants to retail sales data through PostgreSQL, implementing enterprise patterns like Row Level Security, semantic search, and multi-tenant data access.
By the end of this lab, you will be able to:
Modern AI assistants are incredibly powerful but face significant limitations when working with real-world business data:
| Challenge | Description | Business Impact |
|---------------|-----------------|-------------------|
| Static Knowledge | AI models trained on fixed datasets can't access current business data | Outdated insights, missed opportunities |
| Data Silos | Information locked in databases, APIs, and systems AI can't reach | Incomplete analysis, fragmented workflows |
| Security Constraints | Direct database access raises security and compliance concerns | Limited deployment, manual data preparation |
| Complex Queries | Business users need technical knowledge to extract data insights | Reduced adoption, inefficient processes |
Model Context Protocol addresses these challenges by providing:
Throughout this learning path, we'll build an MCP server for Zava Retail, a fictional DIY retail chain with multiple store locations. This realistic scenario demonstrates enterprise-grade MCP implementation.
Zava Retail operates:
Store managers and executives need AI-powered analytics to:
1. Analyze sales performance across stores and time periods
2. Track inventory levels and identify restocking needs
3. Understand customer behavior and purchasing patterns
4. Discover product insights through semantic search
5. Generate reports with natural language queries
6. Maintain data security with role-based access control
The MCP server must provide:
Our MCP server implements a layered architecture optimized for database integration:
┌─────────────────────────────────────────────────────────────┐
│ VS Code AI Client │
│ (Natural Language Queries) │
└─────────────────────┬───────────────────────────────────────┘
│ HTTP/SSE
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Server │
│ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │
│ │ Tool Layer │ │ Security Layer │ │ Config Layer │ │
│ │ │ │ │ │ │ │
│ │ • Query Tools │ │ • RLS Context │ │ • Environment │ │
│ │ • Schema Tools │ │ • User Identity │ │ • Connections │ │
│ │ • Search Tools │ │ • Access Control│ │ • Validation │ │
│ └─────────────────┘ └─────────────────┘ └───────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│ asyncpg
▼
┌─────────────────────────────────────────────────────────────┐
│ PostgreSQL Database │
│ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │
│ │ Retail Schema │ │ RLS Policies │ │ pgvector │ │
│ │ │ │ │ │ │ │
│ │ • Stores │ │ • Store-based │ │ • Embeddings │ │
│ │ • Customers │ │ Isolation │ │ • Similarity │ │
│ │ • Products │ │ • Role Control │ │ Search │ │
│ │ • Orders │ │ • Audit Logs │ │ │ │
│ └─────────────────┘ └─────────────────┘ └───────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│ REST API
▼
┌─────────────────────────────────────────────────────────────┐
│ Azure OpenAI │
│ (Text Embeddings) │
└─────────────────────────────────────────────────────────────┘
| Component | Technology | Purpose |
|---------------|----------------|-------------|
| MCP Framework | FastMCP (Python) | Modern MCP server implementation |
| Database | PostgreSQL 17 + pgvector | Relational data with vector search |
| AI Services | Azure OpenAI | Text embeddings and language models |
| Containerization | Docker + Docker Compose | Development environment |
| Cloud Platform | Microsoft Azure | Production deployment |
| IDE Integration | VS Code | AI Chat and development workflow |
| Tool | Purpose |
|----------|-------------|
| asyncpg | High-performance PostgreSQL driver |
| Pydantic | Data validation and serialization |
| Azure SDK | Cloud service integration |
| pytest | Testing framework |
| Docker | Containerization and deployment |
| Service | Azure Resource | Purpose |
|-------------|-------------------|-------------|
| Database | Azure Database for PostgreSQL | Managed database service |
| Container | Azure Container Apps | Serverless container hosting |
| AI Services | Azure AI Foundry | OpenAI models and endpoints |
| Monitoring | Application Insights | Observability and diagnostics |
| Security | Azure Key Vault | Secrets and configuration management |
Let's explore how different users interact with our MCP server:
User: Sarah, Seattle Store Manager
Goal: Analyze last quarter's sales performance
Natural Language Query:
> "Show me the top 10 products by revenue for my store in Q4 2024"
What Happens:
1. VS Code AI Chat sends query to MCP server
2. MCP server identifies Sarah's store context (Seattle)
3. RLS policies filter data to Seattle store only
4. SQL query generated and executed
5. Results formatted and returned to AI Chat
6. AI provides analysis and insights
User: Mike, Inventory Manager
Goal: Find products similar to a customer request
Natural Language Query:
> "What products do we sell that are similar to 'waterproof electrical connectors for outdoor use'?"
What Happens:
1. Query processed by semantic search tool
2. Azure OpenAI generates embedding vector
3. pgvector performs similarity search
4. Related products ranked by relevance
5. Results include product details and availability
6. AI suggests alternatives and bundling opportunities
User: Jennifer, Regional Manager
Goal: Compare performance across all stores
Natural Language Query:
> "Compare sales by category for all stores in the last 6 months"
What Happens:
1. RLS context set for regional manager access
2. Complex multi-store query generated
3. Data aggregated across store locations
4. Results include trends and comparisons
5. AI identifies insights and recommendations
Our implementation prioritizes enterprise-grade security:
PostgreSQL RLS ensures data isolation:
-- Store managers see only their store's data
CREATE POLICY store_manager_policy ON retail.orders
FOR ALL TO store_managers
USING (store_id = get_current_user_store());
-- Regional managers see multiple stores
CREATE POLICY regional_manager_policy ON retail.orders
FOR ALL TO regional_managers
USING (store_id = ANY(get_user_store_list()));
Each MCP connection includes:
Multiple layers of security:
After completing this introduction, you should understand:
✅ MCP Value Proposition: How MCP bridges AI assistants and real-world data
✅ Business Context: Zava Retail's requirements and challenges
✅ Architecture Overview: Key components and their interactions
✅ Technology Stack: Tools and frameworks used throughout
✅ Security Model: Multi-tenant data access and protection
✅ Usage Patterns: Real-world query scenarios and workflows
Ready to dive deeper? Continue with:
Lab 01: Core Architecture Concepts
Learn about MCP server architecture patterns, database design principles, and the detailed technical implementation that powers our retail analytics solution.
---
Disclaimer: This is a learning exercise using fictional retail data. Always follow your organization's data governance and security policies when implementing similar solutions in production environments.
이 입문 실습은 데이터베이스 통합을 통해 Model Context Protocol (MCP) 서버를 구축하는 방법에 대한 포괄적인 개요를 제공합니다. https://github.com/microsoft/MCP-Server-and-PostgreSQL-Sample-Retail의 Zava Retail 분석 사례를 통해 비즈니스 사례, 기술 아키텍처, 실제 응용 사례를 이해할 수 있습니다.
Model Context Protocol (MCP)은 AI 어시스턴트가 외부 데이터 소스에 실시간으로 안전하게 액세스하고 상호작용할 수 있도록 합니다. 데이터베이스 통합과 결합하면 MCP는 데이터 기반 AI 애플리케이션을 위한 강력한 기능을 제공합니다.
이 학습 경로는 PostgreSQL을 통해 AI 어시스턴트를 소매 판매 데이터에 연결하고, Row Level Security, 의미 검색, 멀티 테넌트 데이터 액세스와 같은 엔터프라이즈 패턴을 구현하는 프로덕션 준비 MCP 서버를 구축하는 방법을 가르칩니다.
이 실습을 완료하면 다음을 수행할 수 있습니다:
현대의 AI 어시스턴트는 매우 강력하지만 실제 비즈니스 데이터와 작업할 때 중요한 한계를 가지고 있습니다:
| 도전 과제 | 설명 | 비즈니스 영향 |
|---------------|-----------------|-------------------|
| 정적 지식 | 고정된 데이터셋으로 훈련된 AI 모델은 현재 비즈니스 데이터를 액세스할 수 없음 | 오래된 통찰력, 기회 상실 |
| 데이터 사일로 | 데이터베이스, API, 시스템에 잠긴 정보로 인해 AI가 접근 불가 | 불완전한 분석, 단편화된 워크플로 |
| 보안 제약 | 직접적인 데이터베이스 액세스는 보안 및 규정 준수 문제를 야기 | 제한된 배포, 수동 데이터 준비 |
| 복잡한 쿼리 | 비즈니스 사용자가 데이터 통찰력을 추출하려면 기술적 지식이 필요 | 낮은 채택률, 비효율적인 프로세스 |
Model Context Protocol은 다음을 통해 이러한 문제를 해결합니다:
이 학습 경로에서는 Zava Retail이라는 가상의 DIY 소매 체인을 위한 MCP 서버를 구축합니다. 이 현실적인 시나리오는 엔터프라이즈급 MCP 구현을 보여줍니다.
Zava Retail은 다음을 운영합니다:
매장 관리자와 임원은 AI 기반 분석을 통해 다음을 수행해야 합니다:
1. 매장 및 기간별 판매 성과 분석
2. 재고 수준 추적 및 재입고 필요성 식별
3. 고객 행동 및 구매 패턴 이해
4. 의미 검색을 통한 제품 통찰력 발견
5. 자연어 쿼리를 사용한 보고서 생성
6. 역할 기반 액세스 제어를 통한 데이터 보안 유지
MCP 서버는 다음을 제공해야 합니다:
우리의 MCP 서버는 데이터베이스 통합에 최적화된 계층형 아키텍처를 구현합니다:
┌─────────────────────────────────────────────────────────────┐
│ VS Code AI Client │
│ (Natural Language Queries) │
└─────────────────────┬───────────────────────────────────────┘
│ HTTP/SSE
▼
┌─────────────────────────────────────────────────────────────┐
│ MCP Server │
│ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │
│ │ Tool Layer │ │ Security Layer │ │ Config Layer │ │
│ │ │ │ │ │ │ │
│ │ • Query Tools │ │ • RLS Context │ │ • Environment │ │
│ │ • Schema Tools │ │ • User Identity │ │ • Connections │ │
│ │ • Search Tools │ │ • Access Control│ │ • Validation │ │
│ └─────────────────┘ └─────────────────┘ └───────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│ asyncpg
▼
┌─────────────────────────────────────────────────────────────┐
│ PostgreSQL Database │
│ ┌─────────────────┐ ┌─────────────────┐ ┌───────────────┐ │
│ │ Retail Schema │ │ RLS Policies │ │ pgvector │ │
│ │ │ │ │ │ │ │
│ │ • Stores │ │ • Store-based │ │ • Embeddings │ │
│ │ • Customers │ │ Isolation │ │ • Similarity │ │
│ │ • Products │ │ • Role Control │ │ Search │ │
│ │ • Orders │ │ • Audit Logs │ │ │ │
│ └─────────────────┘ └─────────────────┘ └───────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│ REST API
▼
┌─────────────────────────────────────────────────────────────┐
│ Azure OpenAI │
│ (Text Embeddings) │
└─────────────────────────────────────────────────────────────┘
| 구성 요소 | 기술 | 목적 |
|---------------|----------------|-------------|
| MCP Framework | FastMCP (Python) | 현대적인 MCP 서버 구현 |
| 데이터베이스 | PostgreSQL 17 + pgvector | 관계형 데이터와 벡터 검색 |
| AI 서비스 | Azure OpenAI | 텍스트 임베딩 및 언어 모델 |
| 컨테이너화 | Docker + Docker Compose | 개발 환경 |
| 클라우드 플랫폼 | Microsoft Azure | 프로덕션 배포 |
| IDE 통합 | VS Code | AI 채팅 및 개발 워크플로 |
| 도구 | 목적 |
|----------|-------------|
| asyncpg | 고성능 PostgreSQL 드라이버 |
| Pydantic | 데이터 검증 및 직렬화 |
| Azure SDK | 클라우드 서비스 통합 |
| pytest | 테스트 프레임워크 |
| Docker | 컨테이너화 및 배포 |
| 서비스 | Azure 리소스 | 목적 |
|-------------|-------------------|-------------|
| 데이터베이스 | Azure Database for PostgreSQL | 관리형 데이터베이스 서비스 |
| 컨테이너 | Azure Container Apps | 서버리스 컨테이너 호스팅 |
| AI 서비스 | Azure AI Foundry | OpenAI 모델 및 엔드포인트 |
| 모니터링 | Application Insights | 관찰 가능성 및 진단 |
| 보안 | Azure Key Vault | 비밀 및 구성 관리 |
다양한 사용자가 MCP 서버와 상호작용하는 방법을 살펴보겠습니다:
사용자: Sarah, 시애틀 매장 관리자
목표: 지난 분기의 판매 성과 분석
자연어 쿼리:
> "2024년 4분기 동안 내 매장에서 매출 기준 상위 10개 제품을 보여줘"
진행 과정:
1. VS Code AI 채팅이 쿼리를 MCP 서버로 전송
2. MCP 서버가 Sarah의 매장 컨텍스트(시애틀)를 식별
3. RLS 정책이 데이터를 시애틀 매장으로 필터링
4. SQL 쿼리가 생성되고 실행됨
5. 결과가 포맷되어 AI 채팅으로 반환
6. AI가 분석 및 통찰력을 제공
사용자: Mike, 재고 관리자
목표: 고객 요청과 유사한 제품 찾기
자연어 쿼리:
> "야외용 방수 전기 커넥터와 유사한 제품을 우리가 판매하나요?"
진행 과정:
1. 쿼리가 의미 검색 도구에 의해 처리됨
2. Azure OpenAI가 임베딩 벡터를 생성
3. pgvector가 유사성 검색 수행
4. 관련 제품이 관련성 순으로 정렬됨
5. 결과에 제품 세부 정보와 가용성이 포함됨
6. AI가 대안 및 번들링 기회를 제안
사용자: Jennifer, 지역 관리자
목표: 모든 매장의 카테고리별 판매 비교
자연어 쿼리:
> "지난 6개월 동안 모든 매장의 카테고리별 판매를 비교해줘"
진행 과정:
1. RLS 컨텍스트가 지역 관리자 액세스로 설정됨
2. 복잡한 다중 매장 쿼리가 생성됨
3. 데이터가 매장 위치별로 집계됨
4. 결과에 트렌드와 비교가 포함됨
5. AI가 통찰력과 추천을 식별
우리의 구현은 엔터프라이즈급 보안을 우선시합니다:
PostgreSQL RLS는 데이터 격리를 보장합니다:
-- Store managers see only their store's data
CREATE POLICY store_manager_policy ON retail.orders
FOR ALL TO store_managers
USING (store_id = get_current_user_store());
-- Regional managers see multiple stores
CREATE POLICY regional_manager_policy ON retail.orders
FOR ALL TO regional_managers
USING (store_id = ANY(get_user_store_list()));
각 MCP 연결에는 다음이 포함됩니다:
다중 보안 계층:
이 소개를 완료한 후 다음을 이해해야 합니다:
✅ MCP 가치 제안: MCP가 AI 어시스턴트와 실제 데이터를 연결하는 방법
✅ 비즈니스 배경: Zava Retail의 요구 사항과 과제
✅ 아키텍처 개요: 주요 구성 요소와 상호작용
✅ 기술 스택: 사용된 도구와 프레임워크
✅ 보안 모델: 멀티 테넌트 데이터 액세스 및 보호
✅ 사용 패턴: 실제 쿼리 시나리오와 워크플로
더 깊이 탐구할 준비가 되셨나요? 다음을 진행하세요:
MCP 서버 아키텍처 패턴, 데이터베이스 설계 원칙, 소매 분석 솔루션을 지원하는 상세 기술 구현에 대해 알아보세요.
---
면책 조항: 이는 가상의 소매 데이터를 사용하는 학습 연습입니다. 프로덕션 환경에서 유사한 솔루션을 구현할 때는 항상 조직의 데이터 거버넌스 및 보안 정책을 따르십시오.
---
면책 조항:
이 문서는 AI 번역 서비스 Co-op Translator를 사용하여 번역되었습니다.
정확성을 위해 최선을 다하고 있으나, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다.
원본 문서의 원어 버전이 권위 있는 출처로 간주되어야 합니다.
중요한 정보의 경우, 전문적인 인간 번역을 권장합니다.
이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.