koharu-mcp 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- koharu_mcp-0.4.0/LICENSE +19 -0
- koharu_mcp-0.4.0/MANIFEST.in +5 -0
- koharu_mcp-0.4.0/PKG-INFO +168 -0
- koharu_mcp-0.4.0/README.md +141 -0
- koharu_mcp-0.4.0/app/__init__.py +0 -0
- koharu_mcp-0.4.0/app/capture.py +62 -0
- koharu_mcp-0.4.0/app/cli.py +181 -0
- koharu_mcp-0.4.0/app/cloud.py +33 -0
- koharu_mcp-0.4.0/app/data/__init__.py +0 -0
- koharu_mcp-0.4.0/app/data/config.json +11 -0
- koharu_mcp-0.4.0/app/data/web/__init__.py +0 -0
- koharu_mcp-0.4.0/app/data/web/index.html +17 -0
- koharu_mcp-0.4.0/app/main.py +293 -0
- koharu_mcp-0.4.0/app/relay.py +119 -0
- koharu_mcp-0.4.0/app/security.py +26 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/PKG-INFO +168 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/SOURCES.txt +22 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/dependency_links.txt +1 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/entry_points.txt +2 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/requires.txt +8 -0
- koharu_mcp-0.4.0/koharu_mcp.egg-info/top_level.txt +1 -0
- koharu_mcp-0.4.0/pyproject.toml +43 -0
- koharu_mcp-0.4.0/requirements.txt +8 -0
- koharu_mcp-0.4.0/setup.cfg +4 -0
koharu_mcp-0.4.0/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Creative Commons Attribution 4.0 International (CC BY 4.0)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Koharu
|
|
4
|
+
|
|
5
|
+
This work is licensed under the Creative Commons Attribution 4.0 International
|
|
6
|
+
License.
|
|
7
|
+
|
|
8
|
+
You are free to share and adapt the material for any purpose, including
|
|
9
|
+
commercial purposes, provided that you give appropriate credit, provide a
|
|
10
|
+
link to the license, and indicate if changes were made.
|
|
11
|
+
|
|
12
|
+
Full legal text:
|
|
13
|
+
https://creativecommons.org/licenses/by/4.0/legalcode
|
|
14
|
+
|
|
15
|
+
License summary:
|
|
16
|
+
https://creativecommons.org/licenses/by/4.0/
|
|
17
|
+
|
|
18
|
+
Attribution:
|
|
19
|
+
"Koharu MCP" by Koharu, licensed under CC BY 4.0.
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: koharu-mcp
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Koharu MCP Windows AI computer-use agent with local approval and 30/60 FPS screen streaming
|
|
5
|
+
Author: Koharu
|
|
6
|
+
License-Expression: CC-BY-4.0
|
|
7
|
+
Keywords: mcp,computer-use,windows,ai-agent,screen-streaming
|
|
8
|
+
Classifier: Development Status :: 4 - Beta
|
|
9
|
+
Classifier: Environment :: Win32 (MS Windows)
|
|
10
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Python: >=3.12
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: fastapi<1,>=0.115
|
|
19
|
+
Requires-Dist: uvicorn[standard]<1,>=0.34
|
|
20
|
+
Requires-Dist: mss<11,>=10
|
|
21
|
+
Requires-Dist: Pillow<13,>=11
|
|
22
|
+
Requires-Dist: numpy<3,>=2
|
|
23
|
+
Requires-Dist: python-dotenv<2,>=1
|
|
24
|
+
Requires-Dist: websockets<18,>=14
|
|
25
|
+
Requires-Dist: PyAutoGUI<1,>=0.9.54
|
|
26
|
+
Dynamic: license-file
|
|
27
|
+
|
|
28
|
+
# Koharu MCP
|
|
29
|
+
|
|
30
|
+
Windows PC를 AI가 화면으로 인식하고 키보드·마우스를 조작하도록 연결하는 MCP 에이전트입니다. **화면 및 입력 권한은 PC 앞의 사용자가 로컬 콘솔에서 직접 승인해야 합니다.**
|
|
31
|
+
|
|
32
|
+
- 웹앱: https://mcp.koharu.live
|
|
33
|
+
- 대시보드: https://mcp.koharu.live/app
|
|
34
|
+
- PyPI 패키지: https://pypi.org/project/koharu-mcp/
|
|
35
|
+
- 버전: 0.4.0
|
|
36
|
+
- 지원: Windows 10/11 x64
|
|
37
|
+
- Python: 3.12 이상
|
|
38
|
+
- 라이선스: CC BY 4.0
|
|
39
|
+
|
|
40
|
+
## 기능
|
|
41
|
+
|
|
42
|
+
- MSS + Pillow 기반 화면 캡처
|
|
43
|
+
- 30 FPS / 60 FPS 프레임 캡처 및 AI 연결로 연속 전송
|
|
44
|
+
- MCP 도구를 통한 현재 화면 이미지 반환
|
|
45
|
+
- 승인 후 마우스 클릭, 텍스트 입력, 키 입력, 스크롤
|
|
46
|
+
- 로컬 승인 콘솔에서 권한 승인 및 즉시 해제
|
|
47
|
+
- Cloudflare Durable Object 기반 브라우저 뷰어 릴레이
|
|
48
|
+
- Neon PostgreSQL 기반 계정, 세션 쿠키, 장치 페어링, 장치 상태 및 감사 로그
|
|
49
|
+
- Vercel 웹앱의 로그인·회원가입·기기 대시보드
|
|
50
|
+
|
|
51
|
+
## 설치
|
|
52
|
+
|
|
53
|
+
Python 3.12 이상이 설치된 Windows PowerShell에서 실행합니다.
|
|
54
|
+
|
|
55
|
+
현재 소스에서 설치하려면 프로젝트 폴더에서 실행합니다.
|
|
56
|
+
|
|
57
|
+
```powershell
|
|
58
|
+
py -m pip install .
|
|
59
|
+
koharu-mcp install
|
|
60
|
+
koharu-mcp start
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
PyPI 공개 업로드가 완료된 뒤에는 아래 명령으로 설치할 수 있습니다.
|
|
64
|
+
|
|
65
|
+
```powershell
|
|
66
|
+
py -m pip install --upgrade koharu-mcp
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
로컬 승인 콘솔은 http://127.0.0.1:8765 입니다. 브라우저에서 **이 PC 제어 승인**을 누르기 전에는 AI의 화면 조회와 입력 도구가 차단됩니다. 권한 해제 버튼은 스트림과 입력 제어를 즉시 중단합니다.
|
|
70
|
+
|
|
71
|
+
설정 파일과 인증 정보는 다음 경로에 저장됩니다.
|
|
72
|
+
|
|
73
|
+
```text
|
|
74
|
+
%LOCALAPPDATA%\KoharuMCP\
|
|
75
|
+
config.json
|
|
76
|
+
.env
|
|
77
|
+
web\index.html
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## MCP 연결
|
|
81
|
+
|
|
82
|
+
로컬 Agent의 JSON-RPC MCP endpoint는 `http://127.0.0.1:8765/oai`입니다. 요청에는 아래 두 헤더가 필요합니다.
|
|
83
|
+
|
|
84
|
+
- `Authorization: Bearer <KOHARU_MCP_TOKEN>`
|
|
85
|
+
- `X-AI-Client-Id: <KOHARU_AI_CLIENT_ID>`
|
|
86
|
+
|
|
87
|
+
실제 값은 `%LOCALAPPDATA%\KoharuMCP\.env`에서 확인합니다. 해당 파일은 외부에 공유하지 마세요.
|
|
88
|
+
|
|
89
|
+
| 도구 | 기능 |
|
|
90
|
+
|---|---|
|
|
91
|
+
| `screen.get_status` | 승인·스트림 상태 |
|
|
92
|
+
| `screen.get_frame` | 현재 화면 JPEG 이미지 |
|
|
93
|
+
| `screen.start_stream` | 30 또는 60 FPS AI 프레임 스트림 시작 |
|
|
94
|
+
| `input.click` | 좌표 클릭 |
|
|
95
|
+
| `input.type_text` | 텍스트 입력 (최대 2,000자) |
|
|
96
|
+
| `input.press_key` | 키 또는 키 조합 입력 |
|
|
97
|
+
| `input.scroll` | 스크롤 |
|
|
98
|
+
| `session.stop` | 스트림 중지 및 세션 종료 |
|
|
99
|
+
|
|
100
|
+
연속 화면은 인증된 로컬 WebSocket `ws://127.0.0.1:8765/oai/ws`에서 전달합니다. 연결 직후 다음 JSON 인증 메시지를 보냅니다.
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{"type":"auth","token":"<KOHARU_MCP_TOKEN>","client_id":"<KOHARU_AI_CLIENT_ID>"}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
프레임은 메타데이터 JSON과 JPEG 바이너리 메시지 쌍으로 전달됩니다. `screen.start_stream`에서 FPS를 30 또는 60으로 지정합니다.
|
|
107
|
+
|
|
108
|
+
## CLI 명령
|
|
109
|
+
|
|
110
|
+
```powershell
|
|
111
|
+
koharu-mcp install # 로컬 설정 및 인증 정보 생성
|
|
112
|
+
koharu-mcp start # MCP 에이전트 실행
|
|
113
|
+
koharu-mcp pair # 로컬 승인 페이지 열기
|
|
114
|
+
koharu-mcp enroll <코드> # 웹 계정에 이 PC 등록
|
|
115
|
+
koharu-mcp status # 실행 상태 확인
|
|
116
|
+
koharu-mcp stop # 에이전트 중지
|
|
117
|
+
koharu-mcp uninstall --yes # 로컬 설정 및 인증 정보 제거
|
|
118
|
+
koharu-mcp --version
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
서버를 종료하려면 실행 중인 PowerShell에서 Ctrl+C를 누릅니다.
|
|
122
|
+
|
|
123
|
+
## 웹 계정 및 장치 연결
|
|
124
|
+
|
|
125
|
+
1. https://mcp.koharu.live/app 에서 이메일과 비밀번호로 계정을 생성합니다.
|
|
126
|
+
2. 대시보드에서 **장치 등록**을 눌러 페어링 코드를 발급합니다.
|
|
127
|
+
3. Windows Agent에서 다음 명령을 실행합니다.
|
|
128
|
+
|
|
129
|
+
```powershell
|
|
130
|
+
koharu-mcp enroll <12자리-페어링-코드>
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
4. 등록된 PC는 Neon DB에 저장되고 heartbeat를 통해 접속 상태를 갱신합니다.
|
|
134
|
+
|
|
135
|
+
비밀번호는 서버에서 scrypt로 해시하고, 브라우저 세션은 HttpOnly·Secure·SameSite 쿠키와 서버 측 토큰 해시로 관리합니다.
|
|
136
|
+
|
|
137
|
+
## 권한 및 보안 경계
|
|
138
|
+
|
|
139
|
+
- 권한은 매 Agent 시작 시 기본 거부 상태입니다.
|
|
140
|
+
- 로컬 콘솔의 명시적 승인이 있어야 화면 조회 및 키보드·마우스 입력이 가능합니다.
|
|
141
|
+
- 승인 취소는 입력 제어, 화면 스트리밍 및 활성 릴레이 세션을 중단합니다.
|
|
142
|
+
- MCP HTTP 및 WebSocket 연결에는 별도의 Bearer 토큰과 클라이언트 ID가 필요합니다.
|
|
143
|
+
- 브라우저 릴레이 뷰어는 읽기 전용입니다. 입력 제어는 로컬 MCP Agent 경로에서만 제공됩니다.
|
|
144
|
+
- 임의 셸 명령 실행 도구는 제공하지 않습니다.
|
|
145
|
+
- `.env`, 장치 토큰, 페어링 코드는 공유하거나 저장소에 커밋하지 마세요.
|
|
146
|
+
|
|
147
|
+
## 개발 및 로컬 빌드
|
|
148
|
+
|
|
149
|
+
```powershell
|
|
150
|
+
py -m pip install -e .
|
|
151
|
+
py -m compileall -q app
|
|
152
|
+
py -m pip check
|
|
153
|
+
koharu-mcp --version
|
|
154
|
+
koharu-mcp --help
|
|
155
|
+
py -m pip install build
|
|
156
|
+
py -m build
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## 배포 상태
|
|
160
|
+
|
|
161
|
+
- 웹앱: Vercel production 배포 완료
|
|
162
|
+
- Neon DB: 계정·장치·세션·감사 로그 스키마 구성
|
|
163
|
+
- Python 패키지: PyPI 배포용 패키징 구성
|
|
164
|
+
- npm은 PC Agent 배포 수단으로 사용하지 않습니다. 루트 `package.json`은 Vercel 서버리스 API 의존성 관리용입니다.
|
|
165
|
+
|
|
166
|
+
## 라이선스
|
|
167
|
+
|
|
168
|
+
Creative Commons Attribution 4.0 International (CC BY 4.0). 저작자 표시와 라이선스 링크, 변경 여부 표시 조건으로 수정·재배포 및 상업적 이용이 가능합니다.
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# Koharu MCP
|
|
2
|
+
|
|
3
|
+
Windows PC를 AI가 화면으로 인식하고 키보드·마우스를 조작하도록 연결하는 MCP 에이전트입니다. **화면 및 입력 권한은 PC 앞의 사용자가 로컬 콘솔에서 직접 승인해야 합니다.**
|
|
4
|
+
|
|
5
|
+
- 웹앱: https://mcp.koharu.live
|
|
6
|
+
- 대시보드: https://mcp.koharu.live/app
|
|
7
|
+
- PyPI 패키지: https://pypi.org/project/koharu-mcp/
|
|
8
|
+
- 버전: 0.4.0
|
|
9
|
+
- 지원: Windows 10/11 x64
|
|
10
|
+
- Python: 3.12 이상
|
|
11
|
+
- 라이선스: CC BY 4.0
|
|
12
|
+
|
|
13
|
+
## 기능
|
|
14
|
+
|
|
15
|
+
- MSS + Pillow 기반 화면 캡처
|
|
16
|
+
- 30 FPS / 60 FPS 프레임 캡처 및 AI 연결로 연속 전송
|
|
17
|
+
- MCP 도구를 통한 현재 화면 이미지 반환
|
|
18
|
+
- 승인 후 마우스 클릭, 텍스트 입력, 키 입력, 스크롤
|
|
19
|
+
- 로컬 승인 콘솔에서 권한 승인 및 즉시 해제
|
|
20
|
+
- Cloudflare Durable Object 기반 브라우저 뷰어 릴레이
|
|
21
|
+
- Neon PostgreSQL 기반 계정, 세션 쿠키, 장치 페어링, 장치 상태 및 감사 로그
|
|
22
|
+
- Vercel 웹앱의 로그인·회원가입·기기 대시보드
|
|
23
|
+
|
|
24
|
+
## 설치
|
|
25
|
+
|
|
26
|
+
Python 3.12 이상이 설치된 Windows PowerShell에서 실행합니다.
|
|
27
|
+
|
|
28
|
+
현재 소스에서 설치하려면 프로젝트 폴더에서 실행합니다.
|
|
29
|
+
|
|
30
|
+
```powershell
|
|
31
|
+
py -m pip install .
|
|
32
|
+
koharu-mcp install
|
|
33
|
+
koharu-mcp start
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
PyPI 공개 업로드가 완료된 뒤에는 아래 명령으로 설치할 수 있습니다.
|
|
37
|
+
|
|
38
|
+
```powershell
|
|
39
|
+
py -m pip install --upgrade koharu-mcp
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
로컬 승인 콘솔은 http://127.0.0.1:8765 입니다. 브라우저에서 **이 PC 제어 승인**을 누르기 전에는 AI의 화면 조회와 입력 도구가 차단됩니다. 권한 해제 버튼은 스트림과 입력 제어를 즉시 중단합니다.
|
|
43
|
+
|
|
44
|
+
설정 파일과 인증 정보는 다음 경로에 저장됩니다.
|
|
45
|
+
|
|
46
|
+
```text
|
|
47
|
+
%LOCALAPPDATA%\KoharuMCP\
|
|
48
|
+
config.json
|
|
49
|
+
.env
|
|
50
|
+
web\index.html
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## MCP 연결
|
|
54
|
+
|
|
55
|
+
로컬 Agent의 JSON-RPC MCP endpoint는 `http://127.0.0.1:8765/oai`입니다. 요청에는 아래 두 헤더가 필요합니다.
|
|
56
|
+
|
|
57
|
+
- `Authorization: Bearer <KOHARU_MCP_TOKEN>`
|
|
58
|
+
- `X-AI-Client-Id: <KOHARU_AI_CLIENT_ID>`
|
|
59
|
+
|
|
60
|
+
실제 값은 `%LOCALAPPDATA%\KoharuMCP\.env`에서 확인합니다. 해당 파일은 외부에 공유하지 마세요.
|
|
61
|
+
|
|
62
|
+
| 도구 | 기능 |
|
|
63
|
+
|---|---|
|
|
64
|
+
| `screen.get_status` | 승인·스트림 상태 |
|
|
65
|
+
| `screen.get_frame` | 현재 화면 JPEG 이미지 |
|
|
66
|
+
| `screen.start_stream` | 30 또는 60 FPS AI 프레임 스트림 시작 |
|
|
67
|
+
| `input.click` | 좌표 클릭 |
|
|
68
|
+
| `input.type_text` | 텍스트 입력 (최대 2,000자) |
|
|
69
|
+
| `input.press_key` | 키 또는 키 조합 입력 |
|
|
70
|
+
| `input.scroll` | 스크롤 |
|
|
71
|
+
| `session.stop` | 스트림 중지 및 세션 종료 |
|
|
72
|
+
|
|
73
|
+
연속 화면은 인증된 로컬 WebSocket `ws://127.0.0.1:8765/oai/ws`에서 전달합니다. 연결 직후 다음 JSON 인증 메시지를 보냅니다.
|
|
74
|
+
|
|
75
|
+
```json
|
|
76
|
+
{"type":"auth","token":"<KOHARU_MCP_TOKEN>","client_id":"<KOHARU_AI_CLIENT_ID>"}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
프레임은 메타데이터 JSON과 JPEG 바이너리 메시지 쌍으로 전달됩니다. `screen.start_stream`에서 FPS를 30 또는 60으로 지정합니다.
|
|
80
|
+
|
|
81
|
+
## CLI 명령
|
|
82
|
+
|
|
83
|
+
```powershell
|
|
84
|
+
koharu-mcp install # 로컬 설정 및 인증 정보 생성
|
|
85
|
+
koharu-mcp start # MCP 에이전트 실행
|
|
86
|
+
koharu-mcp pair # 로컬 승인 페이지 열기
|
|
87
|
+
koharu-mcp enroll <코드> # 웹 계정에 이 PC 등록
|
|
88
|
+
koharu-mcp status # 실행 상태 확인
|
|
89
|
+
koharu-mcp stop # 에이전트 중지
|
|
90
|
+
koharu-mcp uninstall --yes # 로컬 설정 및 인증 정보 제거
|
|
91
|
+
koharu-mcp --version
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
서버를 종료하려면 실행 중인 PowerShell에서 Ctrl+C를 누릅니다.
|
|
95
|
+
|
|
96
|
+
## 웹 계정 및 장치 연결
|
|
97
|
+
|
|
98
|
+
1. https://mcp.koharu.live/app 에서 이메일과 비밀번호로 계정을 생성합니다.
|
|
99
|
+
2. 대시보드에서 **장치 등록**을 눌러 페어링 코드를 발급합니다.
|
|
100
|
+
3. Windows Agent에서 다음 명령을 실행합니다.
|
|
101
|
+
|
|
102
|
+
```powershell
|
|
103
|
+
koharu-mcp enroll <12자리-페어링-코드>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
4. 등록된 PC는 Neon DB에 저장되고 heartbeat를 통해 접속 상태를 갱신합니다.
|
|
107
|
+
|
|
108
|
+
비밀번호는 서버에서 scrypt로 해시하고, 브라우저 세션은 HttpOnly·Secure·SameSite 쿠키와 서버 측 토큰 해시로 관리합니다.
|
|
109
|
+
|
|
110
|
+
## 권한 및 보안 경계
|
|
111
|
+
|
|
112
|
+
- 권한은 매 Agent 시작 시 기본 거부 상태입니다.
|
|
113
|
+
- 로컬 콘솔의 명시적 승인이 있어야 화면 조회 및 키보드·마우스 입력이 가능합니다.
|
|
114
|
+
- 승인 취소는 입력 제어, 화면 스트리밍 및 활성 릴레이 세션을 중단합니다.
|
|
115
|
+
- MCP HTTP 및 WebSocket 연결에는 별도의 Bearer 토큰과 클라이언트 ID가 필요합니다.
|
|
116
|
+
- 브라우저 릴레이 뷰어는 읽기 전용입니다. 입력 제어는 로컬 MCP Agent 경로에서만 제공됩니다.
|
|
117
|
+
- 임의 셸 명령 실행 도구는 제공하지 않습니다.
|
|
118
|
+
- `.env`, 장치 토큰, 페어링 코드는 공유하거나 저장소에 커밋하지 마세요.
|
|
119
|
+
|
|
120
|
+
## 개발 및 로컬 빌드
|
|
121
|
+
|
|
122
|
+
```powershell
|
|
123
|
+
py -m pip install -e .
|
|
124
|
+
py -m compileall -q app
|
|
125
|
+
py -m pip check
|
|
126
|
+
koharu-mcp --version
|
|
127
|
+
koharu-mcp --help
|
|
128
|
+
py -m pip install build
|
|
129
|
+
py -m build
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
## 배포 상태
|
|
133
|
+
|
|
134
|
+
- 웹앱: Vercel production 배포 완료
|
|
135
|
+
- Neon DB: 계정·장치·세션·감사 로그 스키마 구성
|
|
136
|
+
- Python 패키지: PyPI 배포용 패키징 구성
|
|
137
|
+
- npm은 PC Agent 배포 수단으로 사용하지 않습니다. 루트 `package.json`은 Vercel 서버리스 API 의존성 관리용입니다.
|
|
138
|
+
|
|
139
|
+
## 라이선스
|
|
140
|
+
|
|
141
|
+
Creative Commons Attribution 4.0 International (CC BY 4.0). 저작자 표시와 라이선스 링크, 변경 여부 표시 조건으로 수정·재배포 및 상업적 이용이 가능합니다.
|
|
File without changes
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import time
|
|
3
|
+
import threading
|
|
4
|
+
from PIL import Image
|
|
5
|
+
import mss
|
|
6
|
+
|
|
7
|
+
class CaptureEngine:
|
|
8
|
+
def __init__(self, monitor=1, max_width=1600, max_height=900, quality=72):
|
|
9
|
+
self.monitor_index = monitor
|
|
10
|
+
self.max_size = (max_width, max_height)
|
|
11
|
+
self.quality = quality
|
|
12
|
+
self._lock = threading.Lock()
|
|
13
|
+
self._latest = None
|
|
14
|
+
self._running = False
|
|
15
|
+
self._thread = None
|
|
16
|
+
self._meta = {}
|
|
17
|
+
|
|
18
|
+
def _worker(self, fps):
|
|
19
|
+
interval = 1.0 / fps
|
|
20
|
+
deadline = time.perf_counter()
|
|
21
|
+
with mss.mss() as sct:
|
|
22
|
+
monitors = sct.monitors
|
|
23
|
+
index = min(max(1, self.monitor_index), len(monitors) - 1)
|
|
24
|
+
monitor = monitors[index]
|
|
25
|
+
self._meta = {"width": monitor["width"], "height": monitor["height"], "monitor": index}
|
|
26
|
+
while self._running:
|
|
27
|
+
shot = sct.grab(monitor)
|
|
28
|
+
image = Image.frombytes("RGB", shot.size, shot.rgb)
|
|
29
|
+
image.thumbnail(self.max_size, Image.Resampling.LANCZOS)
|
|
30
|
+
buf = io.BytesIO()
|
|
31
|
+
image.save(buf, "JPEG", quality=self.quality, optimize=True)
|
|
32
|
+
with self._lock:
|
|
33
|
+
self._latest = (buf.getvalue(), image.width, image.height, time.time())
|
|
34
|
+
deadline += interval
|
|
35
|
+
delay = deadline - time.perf_counter()
|
|
36
|
+
if delay > 0:
|
|
37
|
+
time.sleep(delay)
|
|
38
|
+
else:
|
|
39
|
+
deadline = time.perf_counter()
|
|
40
|
+
|
|
41
|
+
def start(self, fps=30):
|
|
42
|
+
if fps not in (30, 60):
|
|
43
|
+
raise ValueError("fps must be 30 or 60")
|
|
44
|
+
if self._running:
|
|
45
|
+
return
|
|
46
|
+
self._running = True
|
|
47
|
+
self._thread = threading.Thread(target=self._worker, args=(fps,), daemon=True)
|
|
48
|
+
self._thread.start()
|
|
49
|
+
|
|
50
|
+
def latest(self):
|
|
51
|
+
with self._lock:
|
|
52
|
+
return self._latest
|
|
53
|
+
|
|
54
|
+
def stop(self):
|
|
55
|
+
self._running = False
|
|
56
|
+
if self._thread and self._thread.is_alive():
|
|
57
|
+
self._thread.join(timeout=2)
|
|
58
|
+
self._thread = None
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def metadata(self):
|
|
62
|
+
return dict(self._meta)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import secrets
|
|
7
|
+
import shutil
|
|
8
|
+
import signal
|
|
9
|
+
import sys
|
|
10
|
+
import webbrowser
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from urllib.request import Request, urlopen
|
|
13
|
+
from urllib.error import HTTPError, URLError
|
|
14
|
+
|
|
15
|
+
APP_NAME = "KoharuMCP"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def data_home() -> Path:
|
|
19
|
+
base = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
|
|
20
|
+
return Path(os.environ.get("KOHARU_HOME", Path(base) / APP_NAME))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def initialize() -> Path:
|
|
24
|
+
home = data_home()
|
|
25
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
26
|
+
(home / "web").mkdir(parents=True, exist_ok=True)
|
|
27
|
+
assets = Path(__file__).resolve().parent / "data"
|
|
28
|
+
config = home / "config.json"
|
|
29
|
+
page = home / "web" / "index.html"
|
|
30
|
+
if not config.exists():
|
|
31
|
+
config.write_bytes((assets / "config.json").read_bytes())
|
|
32
|
+
if not page.exists():
|
|
33
|
+
page.write_bytes((assets / "web" / "index.html").read_bytes())
|
|
34
|
+
env_file = home / ".env"
|
|
35
|
+
if not env_file.exists():
|
|
36
|
+
env_file.write_text(
|
|
37
|
+
"KOHARU_MCP_TOKEN=" + secrets.token_urlsafe(48) + "\n"
|
|
38
|
+
"KOHARU_AI_CLIENT_ID=koharu-" + secrets.token_hex(12) + "\n",
|
|
39
|
+
encoding="ascii",
|
|
40
|
+
)
|
|
41
|
+
os.environ["KOHARU_HOME"] = str(home)
|
|
42
|
+
return home
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def command_install(_: argparse.Namespace) -> int:
|
|
46
|
+
home = initialize()
|
|
47
|
+
print(f"Koharu MCP initialized: {home}")
|
|
48
|
+
print("Installation completed. Run: koharu-mcp start")
|
|
49
|
+
print("Local approval console: http://127.0.0.1:8765")
|
|
50
|
+
return 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def command_start(_: argparse.Namespace) -> int:
|
|
54
|
+
if sys.platform != "win32":
|
|
55
|
+
print("Koharu MCP PC agent currently supports Windows 10/11 x64 only.", file=sys.stderr)
|
|
56
|
+
return 2
|
|
57
|
+
home = initialize()
|
|
58
|
+
os.environ["KOHARU_HOME"] = str(home)
|
|
59
|
+
from dotenv import load_dotenv
|
|
60
|
+
load_dotenv(home / ".env", override=False)
|
|
61
|
+
import uvicorn
|
|
62
|
+
config = json.loads((home / "config.json").read_text(encoding="utf-8"))
|
|
63
|
+
pid_file = home / "agent.pid"
|
|
64
|
+
pid_file.write_text(str(os.getpid()), encoding="ascii")
|
|
65
|
+
print(f"Starting Koharu MCP from {home}")
|
|
66
|
+
try:
|
|
67
|
+
uvicorn.run("app.main:app", host=config.get("host", "127.0.0.1"),
|
|
68
|
+
port=int(config.get("port", 8765)), log_level="info")
|
|
69
|
+
finally:
|
|
70
|
+
try:
|
|
71
|
+
pid_file.unlink(missing_ok=True)
|
|
72
|
+
except OSError:
|
|
73
|
+
pass
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def command_pair(_: argparse.Namespace) -> int:
|
|
78
|
+
url = "http://127.0.0.1:8765/"
|
|
79
|
+
print("Open the local console and explicitly approve access on this PC.")
|
|
80
|
+
webbrowser.open(url)
|
|
81
|
+
print(url)
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def command_status(_: argparse.Namespace) -> int:
|
|
86
|
+
try:
|
|
87
|
+
with urlopen("http://127.0.0.1:8765/api/status", timeout=2) as response:
|
|
88
|
+
print(response.read().decode("utf-8"))
|
|
89
|
+
return 0
|
|
90
|
+
except Exception:
|
|
91
|
+
print("STOPPED")
|
|
92
|
+
return 1
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def command_enroll(args: argparse.Namespace) -> int:
|
|
96
|
+
code = str(args.code).strip().upper()
|
|
97
|
+
if len(code) != 12 or any(ch not in "0123456789ABCDEF" for ch in code):
|
|
98
|
+
print("Usage: koharu-mcp enroll <12-character-pairing-code>", file=sys.stderr)
|
|
99
|
+
return 2
|
|
100
|
+
home = initialize()
|
|
101
|
+
base = os.environ.get("KOHARU_CLOUD_URL", "https://mcp.koharu.live").rstrip("/")
|
|
102
|
+
payload = json.dumps({"pairingCode": code, "platform": "windows", "agentVersion": "0.4.0"}).encode()
|
|
103
|
+
request = Request(base + "/api/devices/pair", data=payload,
|
|
104
|
+
headers={"Content-Type": "application/json"}, method="POST")
|
|
105
|
+
try:
|
|
106
|
+
with urlopen(request, timeout=15) as response:
|
|
107
|
+
result = json.loads(response.read().decode("utf-8"))
|
|
108
|
+
except HTTPError as exc:
|
|
109
|
+
print(f"Device enrollment failed: HTTP {exc.code}", file=sys.stderr)
|
|
110
|
+
return 1
|
|
111
|
+
except (URLError, TimeoutError, ValueError) as exc:
|
|
112
|
+
print(f"Could not connect to account server: {exc}", file=sys.stderr)
|
|
113
|
+
return 1
|
|
114
|
+
env_file = home / ".env"
|
|
115
|
+
lines = env_file.read_text(encoding="utf-8").splitlines() if env_file.exists() else []
|
|
116
|
+
updates = {"KOHARU_CLOUD_URL": base, "KOHARU_DEVICE_TOKEN": result["deviceToken"]}
|
|
117
|
+
for key, value in updates.items():
|
|
118
|
+
prefix = key + "="
|
|
119
|
+
for index, line in enumerate(lines):
|
|
120
|
+
if line.startswith(prefix):
|
|
121
|
+
lines[index] = prefix + value
|
|
122
|
+
break
|
|
123
|
+
else:
|
|
124
|
+
lines.append(prefix + value)
|
|
125
|
+
env_file.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
126
|
+
print(f"Device enrolled: {result.get('deviceName', 'Windows PC')}")
|
|
127
|
+
print("Device token saved to the local .env file.")
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def command_stop(_: argparse.Namespace) -> int:
|
|
132
|
+
pid_file = data_home() / "agent.pid"
|
|
133
|
+
if not pid_file.exists():
|
|
134
|
+
print("No running Koharu MCP process was found.")
|
|
135
|
+
return 0
|
|
136
|
+
try:
|
|
137
|
+
pid = int(pid_file.read_text(encoding="ascii").strip())
|
|
138
|
+
os.kill(pid, signal.SIGTERM)
|
|
139
|
+
print(f"Stop signal sent to process {pid}.")
|
|
140
|
+
return 0
|
|
141
|
+
except (OSError, ValueError) as exc:
|
|
142
|
+
print(f"Could not stop Koharu MCP: {exc}", file=sys.stderr)
|
|
143
|
+
return 1
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def command_uninstall(args: argparse.Namespace) -> int:
|
|
147
|
+
if not args.yes:
|
|
148
|
+
print("Confirm removal with: koharu-mcp uninstall --yes")
|
|
149
|
+
return 2
|
|
150
|
+
home = data_home()
|
|
151
|
+
if home.exists():
|
|
152
|
+
shutil.rmtree(home)
|
|
153
|
+
print(f"Removed local Koharu MCP data: {home}")
|
|
154
|
+
return 0
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
158
|
+
parser = argparse.ArgumentParser(prog="koharu-mcp", description="Koharu MCP Windows PC agent")
|
|
159
|
+
parser.add_argument("--version", action="version", version="koharu-mcp 0.4.0")
|
|
160
|
+
sub = parser.add_subparsers(dest="command")
|
|
161
|
+
sub.add_parser("install", help="Initialize local configuration and credentials").set_defaults(func=command_install)
|
|
162
|
+
sub.add_parser("start", help="Start the local MCP agent").set_defaults(func=command_start)
|
|
163
|
+
sub.add_parser("pair", help="Open the local approval console").set_defaults(func=command_pair)
|
|
164
|
+
sub.add_parser("status", help="Show local agent status").set_defaults(func=command_status)
|
|
165
|
+
enroll = sub.add_parser("enroll", help="Enroll this PC into your Koharu account")
|
|
166
|
+
enroll.add_argument("code", help="12-character pairing code")
|
|
167
|
+
enroll.set_defaults(func=command_enroll)
|
|
168
|
+
sub.add_parser("stop", help="Stop the local MCP agent").set_defaults(func=command_stop)
|
|
169
|
+
uninstall = sub.add_parser("uninstall", help="Remove local configuration and credentials")
|
|
170
|
+
uninstall.add_argument("--yes", action="store_true", help="Confirm local data removal")
|
|
171
|
+
uninstall.set_defaults(func=command_uninstall)
|
|
172
|
+
return parser
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main() -> None:
|
|
176
|
+
parser = build_parser()
|
|
177
|
+
args = parser.parse_args()
|
|
178
|
+
if not getattr(args, "command", None):
|
|
179
|
+
parser.print_help()
|
|
180
|
+
raise SystemExit(0)
|
|
181
|
+
raise SystemExit(args.func(args))
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import urllib.request
|
|
5
|
+
from urllib.error import URLError, HTTPError
|
|
6
|
+
|
|
7
|
+
class CloudHeartbeat:
|
|
8
|
+
def __init__(self):
|
|
9
|
+
self.base_url = os.getenv("KOHARU_CLOUD_URL", "https://mcp.koharu.live").rstrip("/")
|
|
10
|
+
self.token = os.getenv("KOHARU_DEVICE_TOKEN", "").strip()
|
|
11
|
+
self.configured = bool(self.token)
|
|
12
|
+
|
|
13
|
+
def _send(self):
|
|
14
|
+
req = urllib.request.Request(
|
|
15
|
+
self.base_url + "/api/devices/heartbeat",
|
|
16
|
+
data=json.dumps({"agentVersion": "0.4.0"}).encode("utf-8"),
|
|
17
|
+
headers={"Authorization": "Bearer " + self.token, "Content-Type": "application/json"},
|
|
18
|
+
method="POST"
|
|
19
|
+
)
|
|
20
|
+
with urllib.request.urlopen(req, timeout=10) as response:
|
|
21
|
+
return json.loads(response.read().decode("utf-8"))
|
|
22
|
+
|
|
23
|
+
async def run(self):
|
|
24
|
+
if not self.configured:
|
|
25
|
+
return
|
|
26
|
+
while True:
|
|
27
|
+
try:
|
|
28
|
+
await asyncio.to_thread(self._send)
|
|
29
|
+
except asyncio.CancelledError:
|
|
30
|
+
raise
|
|
31
|
+
except (URLError, HTTPError, TimeoutError, ValueError):
|
|
32
|
+
pass
|
|
33
|
+
await asyncio.sleep(45)
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="ko"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="theme-color" content="#f7f7f5"><title>Koharu MCP · Local Control</title>
|
|
3
|
+
<style>
|
|
4
|
+
:root{font-family:Inter,"Noto Sans KR",Arial,sans-serif;color:#191a1d;background:#f6f6f3}*{box-sizing:border-box}body{margin:0;padding:30px}.wrap{max-width:920px;margin:auto}header,.panel{background:#fff;border:1px solid #e7e7e2;border-radius:14px;padding:24px;margin-bottom:14px}.eyebrow{font-size:10px;font-weight:800;letter-spacing:1.3px;color:#b65c1b}.top{display:flex;justify-content:space-between;align-items:center}.pill{border-radius:99px;padding:6px 10px;background:#f1f1ee;color:#666;font-size:11px;font-weight:800}h1{font-size:29px;letter-spacing:-1.3px;margin:15px 0 8px}h2{font-size:16px;margin:0 0 12px}p{color:#777;font-size:13px;line-height:1.8}.row{display:flex;align-items:center;gap:10px;flex-wrap:wrap}button,select{font:inherit;border-radius:8px;padding:12px 15px;font-weight:700;border:1px solid #ddd;background:#fff;color:#222}button{cursor:pointer}button:disabled{opacity:.5;cursor:not-allowed}#approve,#remote{background:#191a1d;color:#fff;border-color:#191a1d}#remote{background:#f47721;color:#191a1d;border:0}#stop{background:#fff0ef;color:#a52e25;border-color:#f0d3d0}.notice{padding:13px;background:#fff8f1;border:1px solid #f0dfce;border-radius:9px;color:#79563b;font-size:12px;line-height:1.7}pre{white-space:pre-wrap;word-break:break-word;background:#f6f6f3;padding:13px;border-radius:9px;font-size:11px;color:#555}a{color:#b65c1b;word-break:break-all;font-size:13px;font-weight:700}.result{margin-top:13px;line-height:1.8}.grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}@media(max-width:650px){body{padding:14px}.grid{grid-template-columns:1fr}header,.panel{padding:18px}}
|
|
5
|
+
</style></head><body><main class="wrap">
|
|
6
|
+
<header><div class="top"><div class="eyebrow">KOHARU MCP / WINDOWS AGENT</div><span class="pill" id="approval">승인 대기</span></div><h1>이 PC의 AI 제어 권한</h1><p>화면 캡처와 키보드·마우스 입력을 AI에 허용합니다. 이 화면에서 직접 승인한 뒤에만 AI 도구가 작동하며, 언제든 즉시 해제할 수 있습니다.</p></header>
|
|
7
|
+
<div class="grid"><section class="panel"><h2>1. 로컬 권한</h2><p>승인하면 연결된 AI가 화면을 읽고 마우스 클릭, 텍스트 입력, 키 입력, 스크롤을 수행할 수 있습니다.</p><div class="row"><button id="approve">이 PC 제어 승인</button><button id="stop">즉시 권한 해제</button></div><div class="notice" style="margin-top:13px">승인 버튼은 이 PC의 로컬 콘솔에서만 작동합니다. 권한을 해제하면 스트리밍과 원격 세션도 중지됩니다.</div></section>
|
|
8
|
+
<section class="panel"><h2>2. AI 화면 전송</h2><p>AI로 전송할 화면 프레임 속도를 선택합니다. 60 FPS는 30 FPS보다 네트워크와 CPU 사용량이 높습니다.</p><div class="row"><select id="fps"><option value="30">30 FPS</option><option value="60">60 FPS</option></select><button id="remote">원격 세션 시작</button></div><div id="session" class="result"></div></section></div>
|
|
9
|
+
<section class="panel"><h2>3. 현재 연결 상태</h2><pre id="info">상태 확인 중...</pre></section></main>
|
|
10
|
+
<script>
|
|
11
|
+
const $=s=>document.querySelector(s);
|
|
12
|
+
async function refresh(){try{const r=await fetch('/api/status',{cache:'no-store'});const s=await r.json();$('#approval').textContent=s.approved?'AI 제어 승인됨':'승인 대기';$('#info').textContent=JSON.stringify(s,null,2);$('#approve').disabled=!!s.approved;}catch(e){$('#info').textContent=String(e)}}
|
|
13
|
+
$('#approve').onclick=async()=>{const r=await fetch('/api/approve',{method:'POST'});if(!r.ok)alert('승인 요청 실패');await refresh()};
|
|
14
|
+
$('#stop').onclick=async()=>{const r=await fetch('/api/revoke',{method:'POST'});if(!r.ok)alert('해제 요청 실패');$('#session').textContent='권한이 해제되었습니다.';await refresh()};
|
|
15
|
+
$('#remote').onclick=async()=>{const b=$('#remote');b.disabled=true;b.textContent='연결 중...';try{const r=await fetch('/api/relay/session',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({fps:Number($('#fps').value),ttl_seconds:300})});const d=await r.json();if(!r.ok)throw new Error(d.detail||'세션 생성 실패');$('#session').innerHTML='AI 화면 스트림 세션 생성됨 · '+d.fps+' FPS<br><a target="_blank" rel="noopener noreferrer" href="'+d.viewer_url+'">뷰어 열기</a><br>만료: '+d.expires_at;}catch(e){$('#session').textContent=e.message;}finally{b.disabled=false;b.textContent='원격 세션 시작';await refresh()}};
|
|
16
|
+
refresh();setInterval(refresh,2500);
|
|
17
|
+
</script></body></html>
|