본문으로 건너뛰기

5.10. Python SDK

개요​

이 장은 Python SDK mindwiki_plugin 이 공개하는 이름(__all__)을 모두 정리합니다. 처리기는 프로토콜의 JSON 모양을 dict 로 받고 dict 로 돌려줍니다. 설치 방법과 가장 작은 예시를 먼저 보이고, 이어서 이름을 묶음별 표로 적습니다.

패키지와 버전​

항목값
배포 이름mindwiki-plugin(버전 0.1.0)
가져오는 이름mindwiki_plugin
Python3.10 이상(requires-python = ">=3.10")
의존성표준 라이브러리만

설치​

제품과 함께 받는 배포 파일 mindwiki_plugin-0.1.0-py3-none-any.whl 을 설치합니다. 의존성이 없으므로 인터넷 없이 파일 하나로 설치됩니다.

pip install --no-index ./mindwiki_plugin-0.1.0-py3-none-any.whl

다른 방법도 있습니다.

  • MindWiki 레포가 있으면 pip install <레포>/sdk/python 으로 설치합니다.
  • sdk/python/mindwiki_plugin/ 폴더를 플러그인 옆에 그대로 복사해도 됩니다.
  • wheel 은 레포에서 python3 sdk/python/build_wheel.py dist 로 만듭니다. 이 스크립트는 pip · setuptools 없이 표준 라이브러리만으로 wheel 을 만듭니다.

가장 작은 플러그인​

시작 틀 sdk/template/python/main.py 를 설치한 패키지 기준으로 줄인 것입니다.

import os

from mindwiki_plugin import Handlers, Plugin, Request

MANIFEST = {
"id": "template-plugin-py",
"version": "0.1.0",
"title_i18n": {"ko": "새 플러그인(Python)", "en": "New plugin (Python)"},
"capabilities": ["tools"],
"tools": [{"id": "echo", "read_only": True, "description": "받은 글을 그대로 돌려준다.",
"input_schema": {"type": "object", "properties": {"text": {"type": "string"}}}}],
}

def echo(_r: Request, args: dict) -> dict:
if not isinstance(args.get("text"), str):
return {"text": "text 가 필요합니다", "is_error": True}
return {"text": args["text"]}

def secrets_from_env(env=os.environ) -> dict:
"""지금 비밀(PLUGIN_SECRET)과, 비밀을 바꾸는 동안의 새 비밀(PLUGIN_SECRET_NEXT)."""
secrets = {}
for key, name in (("current", "PLUGIN_SECRET"), ("next", "PLUGIN_SECRET_NEXT")):
if env.get(name):
secrets[key] = env[name]
return secrets

if __name__ == "__main__":
secrets = secrets_from_env() # 코드 · 명령 인자에 넣지 않는다
Plugin(MANIFEST, Handlers(tools={"echo": echo}), secrets).run(port=9100)

공유 비밀은 환경 변수에서 읽습니다. PLUGIN_SECRET 은 지금 비밀이고, PLUGIN_SECRET_NEXT 는 시스템 관리자가 비밀을 바꾸는 동안 넣는 새 비밀입니다. 플러그인이 둘을 함께 받으면 비밀을 바꾸는 동안에도 요청이 거절되지 않습니다. 순서는 4.7. 공유 비밀 바꾸기에 있습니다.

띄우기: Plugin​

Plugin(manifest: dict, handlers: Handlers, secrets: Mapping[str, str], *,
path_prefix: str = "", now: Callable[[], float] = time.time,
max_body: int = 8 << 20)
이름시그니처설명
runrun(host="0.0.0.0", port=8080) -> None표준 라이브러리 서버로 띄우고 멈추지 않습니다
serverserver(host="0.0.0.0", port=8080) -> ThreadingHTTPServer요청마다 스레드 하나로 처리하는 서버를 돌려줍니다. serve_forever() 를 호출해 띄웁니다
wsgiwsgi(environ, start_response) -> list[bytes]WSGI 애플리케이션입니다. gunicorn · uWSGI 에 올립니다
handlehandle(method, path, headers, body) -> tuple[int, bytes]요청 하나를 처리해 (status, JSON 몸통)을 돌려줍니다
PROTOCOLPROTOCOL = 1SDK 가 쓰는 프로토콜 버전
  • secrets 는 위키가 서명에 쓰는 공유 비밀입니다. 바꾸는 동안에는 둘을 넣습니다.
  • path_prefix 는 플러그인이 앞부분 경로 아래에 있을 때 끝점 앞의 경로입니다.
  • now 는 1970년부터의 초를 돌려주는 시계입니다(시험용).
  • max_body 는 요청 몸통의 최대 크기입니다. 기본 8 MiB 입니다.
  • run · server 는 요청을 로그에 남기지 않습니다. 몸통에 값이 들어 있을 수 있기 때문입니다.
  • handle 의 path 는 쿼리를 뺀, 인코딩된 그대로의 경로입니다. headers 는 소문자 이름의 dict 입니다. 다른 HTTP 프레임워크에 붙일 때 씁니다.

동작은 Go SDK 의 Serve 와 같습니다.

  • 모든 요청의 서명을 확인합니다. 서명이 틀리면 401 bad_signature 로 답합니다.
  • GET /manifest 와 GET /health 에 답합니다. health 처리기가 없으면 {"ok": True, "version": …} 으로 답합니다.
  • manifest 에 protocol 이 없으면 [1] 을 넣습니다.
  • 처리기가 PluginError 를 던지면 그 status 와 code 로 답합니다. 다른 예외는 500 retry 로 답합니다.
  • 같은 경로와 같은 x-mindwiki-delivery-id 의 요청에는 첫 답(500 미만)을 다시 줍니다. 최근 1,000건을 메모리에 둡니다.
  • 몸통이 max_body 를 넘으면 413 permanent 로 답합니다.

WSGI 로 띄울 때​

# app.py (MANIFEST · pull · secrets_from_env 는 위와 같이 정의)
plugin = Plugin(MANIFEST, Handlers(pull=pull), secrets_from_env())
application = plugin.wsgi
gunicorn -b 0.0.0.0:8080 app:application

wsgi 는 경로를 RAW_URI, REQUEST_URI, PATH_INFO 순서로 찾습니다. 서명은 인코딩된 경로로 계산하므로, 앞의 두 값을 주는 서버를 씁니다(gunicorn 은 RAW_URI 를 줍니다). PATH_INFO 는 디코딩된 경로입니다. 그래서 경로에 인코딩된 글자가 있으면 서명이 맞지 않을 수 있습니다.

처리기: Handlers​

Handlers 는 dataclass 입니다. 키워드 인자로 필요한 처리 함수만 넣습니다. 넣지 않은 끝점은 not_found 로 답합니다.

이름타입 · 시그니처끝점
healthCallable[[], dict]GET /health
verifyCallable[[Request], None]POST /config/verify
pullCallable[[Request, dict], dict]POST /sync/pull
pushCallable[[Request, dict], dict]POST /sync/push
actionsdict[str, Callable[[Request, dict], dict]]POST /actions/{id}
toolsdict[str, Callable[[Request, dict], dict]]POST /tools/{id}
webhookCallable[[Request, dict], dict]POST /webhook
notifyCallable[[Request, dict], dict]POST /notify

처리기가 받는 dict 와 돌려줄 dict 는 다음과 같습니다.

끝점받는 값돌려줄 값
pull{entity, cursor, limit}{items, next_cursor, more?, estimate?}
push{entity, external_id, changes, snapshot}{} 또는 conflict(remote)
actions{input, context}{message?}
tools인자 dict{text, is_error?}
webhook{headers, body_b64}{ops, pull?}
notify{test, recipient, notification}{message?}
  • actions · tools 의 키는 manifest 의 id 입니다.
  • verify 가 예외 없이 끝나면 SDK 는 {"ok": True} 로 답합니다. verify 가 없을 때도 같습니다.
  • notify 가 없는데 /notify 가 오면 SDK 는 permanent 로 답합니다. 위키는 not_found 를 「받는 사람 없음」으로 처리하기 때문입니다.
  • pull 의 답에 items · next_cursor 가 없으면 SDK 가 빈 값으로 채웁니다. webhook 의 ops 도 같습니다.
  • push · 할 일 · 알림의 답에는 SDK 가 ok: True 를 채웁니다(push 는 conflict 가 없을 때만).
  • 할 일의 context 에는 row · values · queued_at · trigger 가 있습니다. 그 행이 이 설치의 짝일 때만 link · fields 가 더 있습니다.

요청: Request​

이름타입 · 시그니처설명
install · workspacestr설치 ID · 워크스페이스 ID
configdict설치 설정
secretsdict이 끝점에 실린 설치 비밀
actordict{"user", "role"}. 이름 · 메일 없음
delivery_idstrX-MindWiki-Delivery-Id. 없으면 빈 문자열
callbackCallback | None위키를 다시 호출하는 클라이언트. 할 일 · 도구에만 있음
attempt · max_attemptsint할 일의 X-MindWiki-Attempt(n/max). 없으면 둘 다 0
last_attempt속성 bool할 일의 마지막 시도인지 알려 줌. 메서드가 아니라 속성

last_attempt 가 참일 때 retry 로 답하면, 위키는 다시 보내지 않고 할 일을 실패로 끝냅니다. 이때는 실패를 행에 적은 뒤 permanent 로 답합니다.

타입 · 함수 · 상수​

처리기는 프로토콜의 JSON 을 dict 로 다루므로, SDK 에 따로 둔 프로토콜 타입은 없습니다. dict 의 키는 5.1. 끝점의 필드 이름과 같습니다.

이름시그니처설명
conflictconflict(remote: dict) -> dict외부 값이 snapshot 과 다를 때의 push 답을 만듦
parse_attemptparse_attempt(h: str) -> tuple[int, int]"3/8" 을 읽음. 모양이 다르면 (0, 0)
recipient_valuerecipient_value(recipient: dict) -> str방식에 맞는 값(이메일 · 속성 값 · 메신저 ID)을 돌려줌
CAP_NOTIFY문자열 상수 "notify"알림 capability 이름
RECIPIENT_EMAIL · RECIPIENT_ATTRIBUTE · RECIPIENT_HANDLE문자열 상수받는 방식 이름

다른 capability 이름(sync · actions · tools · webhooks)은 상수가 없습니다. manifest 에 문자열로 씁니다.

오류: PluginError​

이름시그니처status · code
err_autherr_auth(msg: str) -> PluginError401 auth
err_retryerr_retry(msg: str) -> PluginError503 retry
err_permanenterr_permanent(msg: str) -> PluginError422 permanent
err_not_founderr_not_found(msg: str) -> PluginError404 not_found
err_unknown_outcomeerr_unknown_outcome(msg: str) -> PluginError502 unknown_outcome
err_invalid_inputerr_invalid_input(msg, fix="", *fields: FieldError)400 invalid_input
notify_errornotify_error(code: str, msg: str) -> PluginError알림 실패. 아래 참고
  • 함수는 PluginError 를 돌려줍니다. 처리기에서 raise 합니다.
  • PluginError 는 Exception 을 상속한 dataclass 입니다. 필드는 status · code · message · fix · errors 이고, to_json() 이 프로토콜의 오류 몸통을 만듭니다.
  • FieldError(path, message) 의 path 는 JSON Pointer 입니다.
  • notify_error 의 code 가 not_found · retry · auth 이면 그 code 로, 그 밖의 값이면 permanent 로 만듭니다.
  • code 상수: CODE_AUTH · CODE_RETRY · CODE_PERMANENT · CODE_INVALID_INPUT · CODE_NOT_FOUND · CODE_UNKNOWN_OUTCOME.

plugins/github-repo/github.py 에 외부 응답을 code 로 바꾸는 예시가 있습니다.

raise err_invalid_input("레포를 찾지 못했습니다", "이름을 확인하고, 비공개 레포면 토큰을 넣으세요",
FieldError("/repo", "확인"))

code 마다 위키가 하는 일은 5.5. 오류 code에 있습니다.

콜백: Callback​

이름시그니처설명
CallbackCallback(url: str, token: str, timeout: float = 15.0)r.callback 으로 받음
opsops(key: str, ops: list[dict]) -> list[dict]연산을 50개까지 보냄
read_bodyread_body(key, entity, external_id, section="") -> dict짝인 행의 본문을 읽음(할 일만)
CallbackError속성 status · code콜백 요청 자체의 거절(problem+json)
OpError속성 coderead_body 에서 위키가 거절한 연산
  • ops 의 결과 하나는 {index, status, code?, error?, ignored?, data?} 입니다.
  • read_body 의 답은 {markdown, rev, edited_at, edited_by} 입니다.
  • key 는 Idempotency-Key 헤더가 됩니다. 키를 비우면 SDK 가 무작위 키를 만듭니다. 다시 보낼 수 있는 일에는 r.delivery_id 를 바탕으로 키를 만듭니다.
  • CallbackError.code 는 bad_token · install_unavailable · rate_limited 등입니다. 목록은 5.6. 콜백 API에 있습니다.
  • OpError.code 는 section_not_found · section_ambiguous · too_large · not_found · forbidden · op_not_allowed 입니다.
  • 콜백은 리다이렉트를 따라가지 않습니다. 토큰이 위키 주소 밖으로 나가지 않게 하기 위해서입니다.

서명: sign · verify​

Plugin 이 서명을 확인하므로 보통은 이 함수들을 직접 쓰지 않습니다. 시험에서, 또는 다른 HTTP 프레임워크에 붙일 때 씁니다.

sign(secret: str, kid: str, time: float, method: str, path: str,
headers: Mapping[str, str], body: bytes) -> str
verify(secrets: Mapping[str, str], sig: str, now: float, method: str, path: str,
headers: Mapping[str, str], body: bytes) -> None
signing_string(t: int, method: str, path: str, headers: Mapping[str, str],
body: bytes) -> bytes
MAX_SKEW_SECONDS = 300
이름설명
signX-MindWiki-Signature 값(t=…,kid=…,sha256=…)을 만듭니다. time 은 초입니다
verify서명을 확인합니다. 틀리면 SignatureError 를 던집니다
signing_string서명할 문자열을 만듭니다
SignatureError서명 거절 예외. 시각이 5분 넘게 다르면 속성 stale 이 참입니다
MAX_SKEW_SECONDS요청 시각과 플러그인 시계의 허용 차이(300초)

헤더 이름 상수(HEADER_SIGNATURE 등)는 __all__ 에 없고 mindwiki_plugin.sign 모듈에 있습니다. 서명 문자열의 규칙은 5.2. 요청 헤더와 서명에 있습니다.

시험​

handle 을 직접 호출하면 서버 없이 시험할 수 있습니다. 서명은 sign 으로 만듭니다.

import json, time
from mindwiki_plugin import sign

body = json.dumps({"args": {"text": "안녕"}}).encode()
headers = {"x-mindwiki-protocol": "1"}
headers["x-mindwiki-signature"] = sign("s", "t", time.time(), "POST", "/tools/echo", headers, body)
status, out = plugin.handle("POST", "/tools/echo", headers, body)

규약 검사는 Go 의 devharness 로 실행합니다. 다음 명령은 MindWiki 레포 루트에서 실행합니다.

WIKI_PLUGIN_SECRET=local-test-only \
go run openmaru.io/cogentai/mindwiki/sdk/go/cmd/devharness -url http://127.0.0.1:9100 check

관련 문서​