gyazo-mcp-server 0.3.0

Local MCP server for Gyazo with HTTP and stdio transport support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
mod app_state;
mod auth;
mod cli;
mod gyazo_api;
mod mcp_oauth;
mod runtime_config;
mod server;
mod tools;

use std::{io, sync::Arc};

use crate::app_state::{AccessTokenRecord, AppState, AuthorizedSession};
use crate::auth::oauth::{self, OAuthCallbackQuery};
use crate::auth::paths;
use crate::auth::config as auth_config;
use crate::cli::{
    Cli, Command, ConfigArgs, ConfigCommand, EnvArgs, EnvCommand, StdioArgs,
};
use crate::gyazo_api::GyazoUserProfile;
use crate::mcp_oauth::{
    authorization_server_metadata_handler, authorize_handler, maybe_complete_mcp_authorization,
    protected_resource_metadata_handler, register_client_handler, require_mcp_bearer_token,
    token_handler,
};
use crate::runtime_config::RuntimeConfig;
use crate::server::GyazoServer;
use anyhow::{Result, anyhow, bail};
use axum::{
    Router,
    extract::{Query, State},
    http::StatusCode,
    middleware,
    response::{IntoResponse, Redirect},
    routing::{get, post},
};
use clap::Parser;
use dotenvy::{dotenv, from_path};
use rmcp::{
    ServiceExt,
    transport::{
        StreamableHttpServerConfig, StreamableHttpService, stdio,
        streamable_http_server::session::local::LocalSessionManager,
    },
};

fn load_env_files() -> Result<()> {
    if let Some(path) = paths::env_file_path()
        && path.exists()
    {
        from_path(path)?;
    }

    if let Err(error) = dotenv()
        && !error.not_found()
    {
        return Err(error.into());
    }

    Ok(())
}

async fn oauth_start_handler(State(app_state): State<Arc<AppState>>) -> impl IntoResponse {
    match oauth::begin_login(app_state.as_ref()) {
        Ok(authorize_url) => Redirect::temporary(&authorize_url).into_response(),
        Err(error) => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            format!("Gyazo OAuth login を開始できませんでした: {error}"),
        )
            .into_response(),
    }
}

async fn oauth_callback_handler(
    State(app_state): State<Arc<AppState>>,
    Query(query): Query<OAuthCallbackQuery>,
) -> impl IntoResponse {
    match maybe_complete_mcp_authorization(app_state.as_ref(), &query).await {
        Ok(Some(response)) => return response,
        Ok(None) => {}
        Err(error) => {
            let (status, message) = error.into_parts();
            return (status, message).into_response();
        }
    }

    match oauth::complete_login(app_state.as_ref(), query).await {
        Ok(message) => (axum::http::StatusCode::OK, message).into_response(),
        Err(error) => {
            let (status, message) = error.into_parts();
            (status, message).into_response()
        }
    }
}

async fn root_handler() -> &'static str {
    "gyazo-mcp-server は起動中です"
}

type DirectAuthOutcome = Result<String, (StatusCode, String)>;

fn direct_auth_response_parts(outcome: &DirectAuthOutcome) -> (StatusCode, String) {
    match outcome {
        Ok(message) => (StatusCode::OK, message.clone()),
        Err((status, message)) => (*status, message.clone()),
    }
}

fn finalize_stdio_auth_outcome(outcome: Option<DirectAuthOutcome>) -> Result<String> {
    match outcome {
        Some(Ok(message)) => Ok(message),
        Some(Err((status, message))) => {
            bail!("Gyazo OAuth 認証に失敗しました (status {status}: {message})");
        }
        None => bail!("OAuth callback を受信できませんでした"),
    }
}

struct DirectAuthState {
    app_state: Arc<AppState>,
    completion: Arc<tokio::sync::Notify>,
    result: Arc<tokio::sync::Mutex<Option<DirectAuthOutcome>>>,
}

async fn complete_direct_auth(
    completion: &tokio::sync::Notify,
    result: &tokio::sync::Mutex<Option<DirectAuthOutcome>>,
    response: DirectAuthOutcome,
) -> (StatusCode, String) {
    let response_parts = direct_auth_response_parts(&response);

    let mut guard = result.lock().await;
    *guard = Some(response);
    drop(guard);
    completion.notify_waiters();

    response_parts
}

async fn direct_oauth_callback_handler(
    State(state): State<Arc<DirectAuthState>>,
    Query(query): Query<OAuthCallbackQuery>,
) -> impl IntoResponse {
    let response = match oauth::complete_login(state.app_state.as_ref(), query).await {
        Ok(message) => Ok(message),
        Err(error) => Err(error.into_parts()),
    };

    complete_direct_auth(state.completion.as_ref(), state.result.as_ref(), response).await
}

async fn resolve_stdio_session(app_state: &AppState) -> Result<AuthorizedSession> {
    let backend_access_token = app_state.resolve_backend_access_token()?.ok_or_else(|| {
        anyhow!("stdio 起動には保存済み OAuth token か GYAZO_MCP_PERSONAL_ACCESS_TOKEN が必要です")
    })?;

    Ok(AuthorizedSession {
        record: AccessTokenRecord {
            backend_access_token,
            gyazo_user: GyazoUserProfile {
                email: String::new(),
                name: String::new(),
                profile_image: String::new(),
                uid: String::new(),
            },
        },
    })
}

async fn run_stdio_auth_flow(
    app_state: Arc<AppState>,
    runtime_config: RuntimeConfig,
) -> Result<()> {
    let authorize_url = oauth::begin_login(app_state.as_ref())?;
    let completion = Arc::new(tokio::sync::Notify::new());
    let result = Arc::new(tokio::sync::Mutex::new(None));
    let auth_state = Arc::new(DirectAuthState {
        app_state,
        completion: completion.clone(),
        result: result.clone(),
    });

    let app = Router::new()
        .route(
            runtime_config.oauth_callback_path(),
            get(direct_oauth_callback_handler),
        )
        .route("/", get(root_handler))
        .with_state(auth_state.clone());

    let listener = tokio::net::TcpListener::bind(runtime_config.bind_address()).await?;
    eprintln!("Gyazo OAuth 認証を開始します。ブラウザで次の URL を開いてください:");
    eprintln!("{authorize_url}");
    eprintln!(
        "callback は {} で待ち受けます。完了するとこのコマンドは終了します。",
        runtime_config.oauth_callback_url()
    );

    let server = axum::serve(listener, app).with_graceful_shutdown(async move {
        completion.notified().await;
    });
    let server_task = tokio::spawn(server.into_future());

    tokio::select! {
        _ = tokio::signal::ctrl_c() => {
            bail!("OAuth 認証を中断しました");
        }
        _ = auth_state.completion.notified() => {}
    }

    server_task.await??;

    let message = finalize_stdio_auth_outcome(result.lock().await.take())?;
    eprintln!("{message}");

    Ok(())
}

async fn run_stdio_server(app_state: Arc<AppState>) -> Result<()> {
    let authorized_session = resolve_stdio_session(app_state.as_ref()).await?;
    let server = GyazoServer::with_fallback_authorized_session(app_state, authorized_session)?;

    tracing::info!("Gyazo MCP stdio サーバーを起動します");

    server.serve(stdio()).await?.waiting().await?;

    Ok(())
}

fn run_config_command(args: ConfigArgs) -> Result<()> {
    match args.command {
        ConfigCommand::Init => runtime_config::init_config(),
        ConfigCommand::Show => runtime_config::show_config(),
        ConfigCommand::Get(get_args) => runtime_config::get_config(&get_args.key),
        ConfigCommand::Set(set_args) => runtime_config::set_config(&set_args.key, &set_args.value),
        ConfigCommand::Unset(unset_args) => runtime_config::unset_config(&unset_args.key),
        ConfigCommand::Path => {
            let path = paths::config_file_path()
                .ok_or_else(|| anyhow!("設定ディレクトリを特定できませんでした"))?;
            println!("{}", path.display());
            Ok(())
        }
    }
}

fn run_env_command(args: EnvArgs) -> Result<()> {
    match args.command {
        EnvCommand::Init => auth_config::init_env(),
        EnvCommand::Show => auth_config::show_env(),
        EnvCommand::Get(get_args) => auth_config::get_env(&get_args.key),
        EnvCommand::Set(set_args) => auth_config::set_env(&set_args.key, &set_args.value),
        EnvCommand::Unset(unset_args) => auth_config::unset_env(&unset_args.key),
        EnvCommand::Path => {
            let path = paths::env_file_path()
                .ok_or_else(|| anyhow!("設定ディレクトリを特定できませんでした"))?;
            println!("{}", path.display());
            Ok(())
        }
    }
}

async fn run_http_server(app_state: Arc<AppState>, runtime_config: RuntimeConfig) -> Result<()> {
    let service_app_state = app_state.clone();
    let service: StreamableHttpService<GyazoServer, LocalSessionManager> =
        StreamableHttpService::new(
            move || GyazoServer::new(service_app_state.clone()).map_err(io::Error::other),
            Arc::new(LocalSessionManager::default()),
            StreamableHttpServerConfig::default(),
        );
    let mcp_routes = Router::new()
        .nest_service(runtime_config.mcp_path(), service)
        .route_layer(middleware::from_fn_with_state(
            app_state.clone(),
            require_mcp_bearer_token,
        ));

    let app = Router::new()
        .route(
            runtime_config.protected_resource_metadata_root_path(),
            get(protected_resource_metadata_handler),
        )
        .route(
            &runtime_config.protected_resource_metadata_path(),
            get(protected_resource_metadata_handler),
        )
        .route(
            runtime_config.authorization_server_metadata_path(),
            get(authorization_server_metadata_handler),
        )
        .route(
            runtime_config.authorization_endpoint_path(),
            get(authorize_handler),
        )
        .route(runtime_config.token_endpoint_path(), post(token_handler))
        .route(
            runtime_config.registration_endpoint_path(),
            post(register_client_handler),
        )
        .route("/", get(root_handler))
        .route(runtime_config.oauth_start_path(), get(oauth_start_handler))
        .route(
            runtime_config.oauth_callback_path(),
            get(oauth_callback_handler),
        )
        .merge(mcp_routes)
        .with_state(app_state);

    let listener = tokio::net::TcpListener::bind(runtime_config.bind_address()).await?;
    tracing::info!(
        bind_address = %runtime_config.bind_address(),
        mcp_url = %runtime_config.mcp_url(),
        protected_resource_metadata_url = %runtime_config.protected_resource_metadata_url(),
        authorization_server_metadata_url = %runtime_config.authorization_server_metadata_url(),
        authorization_endpoint_url = %runtime_config.authorization_endpoint_url(),
        token_endpoint_url = %runtime_config.token_endpoint_url(),
        registration_endpoint_url = %runtime_config.registration_endpoint_url(),
        oauth_start_url = %runtime_config.oauth_start_url(),
        oauth_callback_url = %runtime_config.oauth_callback_url(),
        "Gyazo MCP HTTP サーバーを起動します",
    );

    axum::serve(listener, app)
        .with_graceful_shutdown(async {
            let _ = tokio::signal::ctrl_c().await;
        })
        .await?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    if let Some(dir) = &cli.config_dir {
        paths::set_config_dir_override(std::path::PathBuf::from(dir));
    } else {
        // CLI override がなければ、デフォルト .env から GYAZO_MCP_CONFIG_DIR を
        // 先読みして環境変数にセットする。load_env_files() より前に行うのは、
        // load_env_files() 自体が paths::config_dir() → env_file_path() を
        // 経由するため、先に config_dir を確定させておく必要があるため。
        if let Some(dir) = auth_config::read_config_dir_from_default_env() {
            // Safety: main の最初期でまだ他スレッドは起動していない
            unsafe { std::env::set_var("GYAZO_MCP_CONFIG_DIR", &dir) };
        }
    }

    // config/env コマンドは設定ファイルの読み書きを自前で行うため、
    // load_env_files() や RuntimeConfig::load() より前にディスパッチする。
    // これにより config.toml が壊れていても config set で復旧できる。
    match cli.command {
        Some(Command::Config(args)) => return run_config_command(args),
        Some(Command::Env(args)) => return run_env_command(args),
        _ => {}
    }

    load_env_files()?;
    let runtime_config = RuntimeConfig::load()?;

    tracing_subscriber::fmt()
        .with_env_filter(runtime_config.tracing_env_filter())
        .with_writer(std::io::stderr)
        .init();
    let app_state = Arc::new(AppState::new(runtime_config.clone())?);

    match cli.command {
        Some(Command::Stdio(StdioArgs { auth: true })) => {
            run_stdio_auth_flow(app_state, runtime_config).await?
        }
        Some(Command::Stdio(StdioArgs { auth: false })) => run_stdio_server(app_state).await?,
        Some(Command::Config(_) | Command::Env(_)) => unreachable!(),
        None => run_http_server(app_state, runtime_config).await?,
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::{sync::Arc, time::Duration};

    use axum::http::StatusCode;
    use tokio::time::timeout;

    use super::{complete_direct_auth, direct_auth_response_parts, finalize_stdio_auth_outcome};

    #[test]
    fn direct_auth_response_parts_returns_ok_for_success() {
        let response = direct_auth_response_parts(&Ok("done".to_string()));

        assert_eq!(response, (StatusCode::OK, "done".to_string()));
    }

    #[test]
    fn direct_auth_response_parts_preserves_failure_parts() {
        let response =
            direct_auth_response_parts(&Err((StatusCode::BAD_REQUEST, "bad request".to_string())));

        assert_eq!(
            response,
            (StatusCode::BAD_REQUEST, "bad request".to_string())
        );
    }

    #[test]
    fn finalize_stdio_auth_outcome_returns_success_message() {
        let message = finalize_stdio_auth_outcome(Some(Ok("saved".to_string()))).unwrap();

        assert_eq!(message, "saved");
    }

    #[test]
    fn finalize_stdio_auth_outcome_returns_failure_error() {
        let error = finalize_stdio_auth_outcome(Some(Err((
            StatusCode::BAD_GATEWAY,
            "exchange failed".to_string(),
        ))))
        .unwrap_err();

        assert_eq!(
            error.to_string(),
            "Gyazo OAuth 認証に失敗しました (status 502 Bad Gateway: exchange failed)"
        );
    }

    #[test]
    fn finalize_stdio_auth_outcome_returns_missing_callback_error() {
        let error = finalize_stdio_auth_outcome(None).unwrap_err();

        assert_eq!(error.to_string(), "OAuth callback を受信できませんでした");
    }

    #[tokio::test]
    async fn complete_direct_auth_notifies_all_waiters_and_stores_result() {
        let completion = Arc::new(tokio::sync::Notify::new());
        let result = tokio::sync::Mutex::new(None);

        let waiter_one = completion.notified();
        let waiter_two = completion.notified();

        let response = complete_direct_auth(&completion, &result, Ok("saved".to_string())).await;

        assert_eq!(response, (StatusCode::OK, "saved".to_string()));
        assert_eq!(result.lock().await.as_ref(), Some(&Ok("saved".to_string())));
        timeout(Duration::from_millis(100), waiter_one)
            .await
            .expect("1つ目の waiter が起きる必要があります");
        timeout(Duration::from_millis(100), waiter_two)
            .await
            .expect("2つ目の waiter も起きる必要があります");
    }
}