Spaces:
Sleeping
Sleeping
| # app.py | |
| import os | |
| import gradio as gr | |
| # --- コア処理(ここに本来のツール処理を書く) --- | |
| def handle_request(q: str, user_label: str) -> str: | |
| # 実際にはここから外部API呼び出し・DB操作などを行う | |
| return f"[{user_label}] You said: {q}" | |
| # --- 認証+実行:キーが無いときは guest --- | |
| def my_tool(q: str, dev_token: str, request: gr.Request) -> str: | |
| """ | |
| Simple demo tool that echoes the user query with authentication context. | |
| Args: | |
| q (str): ユーザーの入力テキスト。 | |
| dev_token (str): 開発・デバッグ用に手動で指定するAPIキー。 | |
| request (gr.Request): HTTPリクエスト。Authorizationヘッダを含む。 | |
| Returns: | |
| str: "guest" または "user:xxxx" と共に入力テキストを返す。 | |
| """ | |
| # 認証処理は省略(前と同じ) | |
| auth = request.headers.get("authorization") | |
| if not auth and dev_token: | |
| auth = f"Bearer {dev_token.strip()}" | |
| if not auth: | |
| return f"[guest] You said: {q}" | |
| token = auth.split(" ", 1)[1] if " " in auth else auth | |
| short = token[:6] + "..." if len(token) > 6 else token | |
| return f"[user:{short}] You said: {q}" | |
| # ---- Gradio UI ---- | |
| examples = [ | |
| ["Hello world", ""], # 1) guest | |
| ["Check my status", "sk_test_123456"], # 2) ダミーAPIキー | |
| ["Fetch HF data", "hf_dummy_token_abcdef"], # 3) HFトークン例 | |
| ] | |
| with gr.Blocks() as demo: | |
| gr.Markdown("### Gradio MCP 認証デモ(キー無し=guest)") | |
| q = gr.Textbox(label="Query", placeholder="Type something") | |
| dev_token = gr.Textbox( | |
| label="API Token (開発用オプション)", | |
| type="password", | |
| placeholder="sk_xxx / hf_xxx" | |
| ) | |
| out = gr.Textbox(label="Result", lines=3) | |
| run = gr.Button("Run") | |
| run.click(my_tool, inputs=[q, dev_token], outputs=[out]) | |
| gr.Examples( | |
| examples=examples, | |
| inputs=[q, dev_token], | |
| outputs=[out], | |
| fn=my_tool, | |
| cache_examples=False, | |
| ) | |
| # MCPサーバを同時起動(SSEは非推奨。/gradio_api/mcp/ を使用) | |
| demo.launch( | |
| mcp_server=True, | |
| ssr_mode=True, # SSRログの⚡表示用(不要ならFalse) | |
| server_name="0.0.0.0", | |
| server_port=int(os.getenv("PORT", "7860")), | |
| ) | |