본문 바로가기
Python/MCP

[MCP] Server, Client 기본 (Python)

by 미눅스[멘토] 2025. 9. 26.
728x90

순서대로 차근차근 진행.

0. Node.js 설치

https://deahan.tistory.com/413

 

[React] 272샘의 React1 (Node.Js설치)

https://nodejs.org/en Node.js — Run JavaScript EverywhereNode.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.nodejs.orgNode.js 홈페이지 에서 다운받을 수 있지만 그렇게 하지 않을 것이다이유는 node는 버전

deahan.tistory.com

Node.js가 설치되어 있지 않다면 위에 사이트에 가서 node.js설치하고 오자.

 

MCP를 활용하는 과정에서 npx 명령어를 사용하게 된다. npx는 Node.js에 포함된 실행 도구로, MCP 서버를 실행하거나 MCP 관련 도구를 다운로드하고 실행할 때 사용된다.

 

예를 들어, Claoude Desktop이나 Cursor에 MCP 서버를 등록할 때 사용하는 설정 파일(claoude_desktop_config.json, mcp.json)에는 다음과 같은 형식으로 MCP 실행 명령이 들어간다.

"myServer": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-fetch"],
  "env": {
    "MCP_SERVER_URL": "https://my-server.com/mcp"
  }
}
  • command 필드에 npx가지정되어 있다. 이는 MCP 서버를 실행하기 위해 npx 명령어를 사용한다는 것을 의미한다. 

이처럼 MCP 호스트는 MCP 서버를 npx 명령어로 통해 실행한다. 따라서 Node.js가 설치되어 있어야 npx도 함께 사용할 수 있다.

 

1.파이썬 MCP SDK 선정 

본인은 FastMCP 사용 예정

  MCP Python SDKFastMCP
목적 MCP 명세의 표준 구현 고성능 컨텍스트 처리 및 실서비스 적용에 초점
성능 순수 파이썬 기반, 일반적인 수준 Rust 기반 고성능 구현, 낮은 지연 시간
내부 구현 순수 파이썬 Rust(PyO3 등 활용) 기반 코어 로직
적용 사례 학습, 테스트, 간단한 컨텍스트 처리 대규모 트래픽/고성능 요구 서비스, 프로덕션 환경
웹 프레임워크 연동 제한적 FastAPI 등과의 통합 지원, ASGI 친화적 구조
API 설계 명세 중심의 설계 개발자 편의 중심의 간소화된 API

 

 

2. uv 설치 (Windows 기준)

터미널(cmd)을 열고 다음 명령어를 입력

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

 

실행 결과

  uv.exe
  uvx.exe
  uvw.exe
everything's installed!
# ... (생략) ...

 

설치 확인

#터미널을 새로 열고 다음 명령어로 uv의 정상 설치 여부를 확인합니다.
uv

 

실행 결과

An extremely fast Python package manager.

Usage: uv [OPTIONS] <COMMAND>

Commands:
  run      Run a command or script
  init     Create a new project
  add      Add dependencies to the project
  remove   Remove dependencies from the project
# ... (생략) ...

 

 

3.FastMCP 설치하기

 

프로젝트 구조 설명

D:\project\my-mcp-server
 ├── server.py
 ├── client.py
 ├── pyproject.toml
 ├── README.md
 └── ... (생략) ...

프로젝트: my-mcp-server
디렉토리: D:\project\my-mcp-server
스크립트: server.py

 

 

터미널(cmd)을 열고 아래의 명령어를 입력하여 프로젝트 디렉토리로 이동

d:
cd project

 

프로젝트 초기화

#my-mcp-server 프로젝트를 초기화
uv init my-mcp-server

 

실행 결과

Initialized project `my-mcp-server` at `D:\project\my-mcp-server`

 

FastMCP 설치

cd my-mcp-server
uv add fastmcp

 

실행 결과

#실행 결과
Using CPython 3.13.5
Creating virtual environment at: .venv
Resolved 36 packages in 419ms
Prepared 13 packages in 315ms
░░░░░░░░░░░░░░░░░░░░ [0/35] Installing wheels...
...
Installed 35 packages in 352ms
 + annotated-types==0.7.0
 + anyio==4.9.0
# ... (생략) ...

 

설치 확인

fastmcp version

 

실행 결과

#실행결과
'fastmcp'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다

fastmcp version 명령어가 인식되지 않는다는 오류가 발생, 이는 fastmcp가 설치된 .venv 가상 환경을 활성화하지 않고 명령어를 실행했기 때문

 

 

uv를 사용하여 FastMCP 명령어를 실행

uv run fastmcp version

 

실행 결과 

FastMCP version:                                              2.8.1
MCP version:                                                  1.9.4
Python version:                                              3.13.5
Platform:                                                Windows...
FastMCP root path: D:\project\my-mcp-server\.venv\Lib\site-packages

 

 

4.FastMCP 서버  구축

my-mcp-server 디렉토리 안에 server.py 파일 생성

 

server.py

from fastmcp import FastMCP

mcp = FastMCP(name="calculator")

@mcp.tool
def multiply(a: float, b: float) -> float:
    """Multiplies two numbers together."""
    return a * b

if __name__ == "__main__":
    mcp.run()

 

 

5FastMCP Server 구축

my-mcp-server 디렉토리 안에 client.py 파일 생성

 

client.py

import asyncio
from fastmcp import Client

# MCP 서버를 연결하여 MCP 클라이언트를 생성합니다.
client = Client("server.py")

async def main():
    async with client:
        print(f"Client connected: {client.is_connected()}")

        # 서버의 도구 목록을 가져옵니다.
        tools = await client.list_tools()
        print(f"Available tools: {tools}")

        # 만약 "multiply" 도구가 있다면...
        if any(tool.name == "multiply" for tool in tools):
            # 서버의 "multiply" 도구를 호출하여 결과를 가져옵니다.
            result = await client.call_tool("multiply", {"a": 3, "b": 7})
            print(f"multiply result: {result}")

    print(f"Client connected: {client.is_connected()}")

if __name__ == "__main__":
    asyncio.run(main())

 

 

프로젝트 디렉토리(D:\project\my-mcp-server)에서 터미널을 열고 아래의 명령어를 입력하여 클라이언트를 실행

uv run client.py

 

실행 결과

INFO     Starting MCP server 'calculator' with        server.py:1168                             transport 'stdio'
Client connected: True
Available tools: [Tool(name='multiply', description='Multiplies two numbers together.', inputSchema={'properties': {'a': {'title': 'A', 'type': 'number'}, 'b': {'title': 'B', 'type': 'number'}}, 'required': ['a', 'b'], 'type': 'object'}, annotations=None)]
multiply result: [TextContent(type='text', text='21.0', annotations=None)]
Client connected: False

 

Starting MCP server ... 메시지를 통해 클라이언트가 서버를 자동으로 실행하고 있음을 확인할 수 있음

'Python > MCP' 카테고리의 다른 글

[MCP] LLM과 MCP 통합하기 (OpenAI)  (1) 2025.09.26