diff options
| author | tanaka takashi <isazaka@gmail.com> | 2026-08-09 23:19:24 +0900 |
|---|---|---|
| committer | tanaka takashi <isazaka@gmail.com> | 2026-08-09 23:19:24 +0900 |
| commit | 788df5e1d86c1bd91571d2b9cd1559599b65c9d6 (patch) | |
| tree | 3d1d9bec9e8318bfc6749f9f8f1727436e3d6af1 /src/Agent.App | |
| parent | b07b41cd435991cd254957af79055080c85b346e (diff) | |
feat(mcp): migrate server to MCP 2026-07-28
Replace the MCP 1.4.1 stateful HTTP design with the official C# SDK 2.0.0 stateless transport. The SDK now owns protocol negotiation, server/discover, standard MCP headers, GET and DELETE handling, error serialization, caching hints, and legacy initialize compatibility; production code no longer maintains a custom wire-protocol workaround for MCP Inspector.
Separate transport state from application conversation state. HTTP does not issue Mcp-Session-Id, while the existing session_id remains an Agent conversation identifier. Preserve agent_run and agent_status for clients without Tasks support and add the official ModelContextProtocol.Extensions.Tasks 2.0.0 path for capable clients.
Add persistent MCP Task storage with atomic JSON replacement, user-only state location, configurable TTL and poll interval, restart recovery, cancellation correlation, and public Agent-to-MCP state mapping. Keep conformance-only tools and protocol exception fixtures in a test host so they cannot enter the Release Bundle.
Run administrator, BFE, WFP transaction, and filter add/delete preflight before binding. Fail fast with exit code 2 and actionable localized diagnostics when sandbox enforcement is unavailable. Emit ready only after the listener starts and keep stdio stdout protocol-pure.
Add shared rotating application and HTTP request logs. Record real socket endpoints, connection and trace identifiers, method, path, result, timing, media metadata, User-Agent, and MCP metadata. Do not trust X-Forwarded-For and do not log authorization, cookies, query data, request or response bodies, prompts, images, or Base64 payloads.
Add typed logging and Tasks configuration, Japanese and English messages, protocol and operations documentation, design/specification deltas, traceability, and exact conformance acquisition/offline runner scripts for @modelcontextprotocol/conformance 0.2.0-alpha.11. Node remains test-only and is not a runtime dependency.
Conformance evidence: server-stateless passed 28 of 28 checks with zero unexpected failures; DNS rebinding and multiple POST stream scenarios passed. The alpha Tasks lifecycle/cancel/error/required-task checks passed, while its wire-schema validator misclassifies CreateTaskResult and its MRTR composition remains incompatible with SDK 2.0.0. The aggregate conformance Gate is therefore recorded as PARTIAL, not PASS. Test-host fixture gaps for tools-list descriptions, JSON Schema diagnostics, caching fixtures, and a header-validation/required-Task capability conflict are also recorded without expected-failure masking.
Verification: Release build passed with 0 warnings and 0 errors; Planner tests 10/10 and Core tests 47/47 passed with skip 0. The last Windows suite run passed 19/25; five WFP cases require an elevated token and one symlink case requires unavailable host privilege, so the elevated security Gate remains open. A win-x64 self-contained 1.0.0 Bundle and ZIP were regenerated under build/Release/publish; runtime check was intentionally skipped in this non-elevated session. Evidence remains under ignored artifacts/evidence/mcp-2026-07-28.
Harden release regeneration when another shell holds the previous Bundle directory as its current directory: validate the target and remove only its children instead of deleting the directory itself. build/ and artifacts/ remain excluded from Git.
Diffstat (limited to 'src/Agent.App')
| -rw-r--r-- | src/Agent.App/Configuration/AgentConfiguration.cs | 4 | ||||
| -rw-r--r-- | src/Agent.App/Configuration/ConfigurationLoader.cs | 2 | ||||
| -rw-r--r-- | src/Agent.App/Logging/McpHostLogObserver.cs | 76 | ||||
| -rw-r--r-- | src/Agent.App/Logging/RollingFileLog.cs | 55 | ||||
| -rw-r--r-- | src/Agent.App/Logging/RollingFileWriter.cs | 50 | ||||
| -rw-r--r-- | src/Agent.App/Program.cs | 30 |
6 files changed, 181 insertions, 36 deletions
diff --git a/src/Agent.App/Configuration/AgentConfiguration.cs b/src/Agent.App/Configuration/AgentConfiguration.cs index 800286b..362b889 100644 --- a/src/Agent.App/Configuration/AgentConfiguration.cs +++ b/src/Agent.App/Configuration/AgentConfiguration.cs @@ -23,10 +23,12 @@ public sealed class McpOptions public string Transport { get; set; } = "stdio"; public HttpOptions Http { get; set; } = new(); public ImageOptions Images { get; set; } = new(); + public McpTaskOptions Tasks { get; set; } = new(); } public sealed class HttpOptions { public string Host { get; set; } = "127.0.0.1"; public int Port { get; set; } = 8080; } public sealed class ImageOptions { public int MaxCount { get; set; } = 4; public long MaxBytesEach { get; set; } = 10 * 1024 * 1024; public long MaxTotalBytes { get; set; } = 20 * 1024 * 1024; } +public sealed class McpTaskOptions { public int TimeToLiveHours { get; set; } = 24; public int PollIntervalMs { get; set; } = 1000; } public sealed class RuntimeOptions { public string UserSystemPrompt { get; set; } = "prompts/user-system.md"; public int MaxIterations { get; set; } = 128; public int SameFailureLimit { get; set; } = 5; } public sealed class OllamaConfiguration @@ -73,4 +75,4 @@ public sealed class FileEditOptions { public int MemoryBackupLimitMb { get; set; public sealed class LimitOptions { public long WholeReadBytes { get; set; } = 1024 * 1024; public int SearchMaxResults { get; set; } = 1000; public int TailMaxLines { get; set; } = 10000; public double ContextSummaryRatio { get; set; } = 0.8; } public sealed class LocalizationOptions { public string Directory { get; set; } = "config/locales"; public string Fallback { get; set; } = "en"; } public sealed class SkillOptions { public string Directory { get; set; } = "skills"; } -public sealed class LoggingOptions { public string Directory { get; set; } = "logs"; public long MaxFileBytes { get; set; } = 10 * 1024 * 1024; public int RetainedFiles { get; set; } = 5; } +public sealed class LoggingOptions { public string Directory { get; set; } = "logs"; public string Level { get; set; } = "information"; public bool HttpRequests { get; set; } = true; public long MaxFileBytes { get; set; } = 10 * 1024 * 1024; public int RetainedFiles { get; set; } = 5; } diff --git a/src/Agent.App/Configuration/ConfigurationLoader.cs b/src/Agent.App/Configuration/ConfigurationLoader.cs index b6c4c2d..298a143 100644 --- a/src/Agent.App/Configuration/ConfigurationLoader.cs +++ b/src/Agent.App/Configuration/ConfigurationLoader.cs @@ -44,6 +44,7 @@ public static partial class ConfigurationLoader if (value.Mcp.Http.Port is < 1 or > 65535) Throw("mcp.http.port is outside 1..65535."); if (value.Mcp.Images.MaxCount < 0 || value.Mcp.Images.MaxBytesEach <= 0 || value.Mcp.Images.MaxTotalBytes <= 0) Throw("mcp.images limits must be positive."); if (value.Mcp.Images.MaxTotalBytes < value.Mcp.Images.MaxBytesEach) Throw("mcp.images.max_total_bytes must be >= max_bytes_each."); + if (value.Mcp.Tasks.TimeToLiveHours <= 0 || value.Mcp.Tasks.PollIntervalMs <= 0) Throw("mcp.tasks TTL and poll interval must be positive."); if (value.Agent.MaxIterations <= 0 || value.Agent.SameFailureLimit <= 0) Throw("agent iteration limits must be positive."); if (!Uri.TryCreate(value.Ollama.Endpoint, UriKind.Absolute, out Uri? endpoint) || endpoint.Scheme is not ("http" or "https")) Throw("ollama.endpoint must be an absolute HTTP(S) URI."); if (string.IsNullOrWhiteSpace(value.Ollama.Model)) Throw("ollama.model is required."); @@ -62,6 +63,7 @@ public static partial class ConfigurationLoader } if (value.FileEdit.MemoryBackupLimitMb <= 0 || value.Limits.WholeReadBytes <= 0 || value.Limits.SearchMaxResults <= 0 || value.Limits.TailMaxLines <= 0 || value.Limits.ContextSummaryRatio is <= 0 or >= 1) Throw("file/context limits are invalid."); if (value.Logging.MaxFileBytes <= 0 || value.Logging.RetainedFiles < 1) Throw("logging limits are invalid."); + if (value.Logging.Level is not ("information" or "warning" or "error" or "fatal")) Throw("logging.level must be information, warning, error, or fatal."); RequireFile(baseDirectory, value.Agent.UserSystemPrompt, "agent.user_system_prompt"); RequireDirectory(baseDirectory, value.Localization.Directory, "localization.directory"); diff --git a/src/Agent.App/Logging/McpHostLogObserver.cs b/src/Agent.App/Logging/McpHostLogObserver.cs new file mode 100644 index 0000000..b1410e8 --- /dev/null +++ b/src/Agent.App/Logging/McpHostLogObserver.cs @@ -0,0 +1,76 @@ +using System.Globalization; +using System.Text.Json; +using Agent.Core.Localization; +using Agent.Mcp; +using System.Collections.Concurrent; + +namespace Agent.App.Logging; + +public sealed class McpHostLogObserver : IMcpHostObserver, IDisposable +{ + private readonly RollingFileLog _application; + private readonly RollingFileWriter? _http; + private readonly LocaleCatalog _locale; + private readonly string _logDirectory; + private readonly ConcurrentDictionary<string, byte> _observedConnections = new(StringComparer.Ordinal); + + public McpHostLogObserver(RollingFileLog application, LocaleCatalog locale, string logDirectory, + bool httpRequests, long maxBytes, int retainedFiles) + { + _application = application; + _locale = locale; + _logDirectory = logDirectory; + if (httpRequests) _http = new RollingFileWriter(Path.Combine(logDirectory, "http.jsonl"), maxBytes, retainedFiles); + } + + public void Ready(McpReadyInfo info) + { + string message = info.Transport == "http" + ? _locale.Format("app.ready.http", new Dictionary<string, object?> + { + ["endpoint"] = info.Endpoint, ["protocol"] = info.ProtocolVersion, ["stateless"] = info.Stateless.ToString().ToLowerInvariant(), + ["fallback"] = info.LegacyFallback.ToString().ToLowerInvariant(), ["pid"] = info.ProcessId, ["logs"] = _logDirectory + }) + : _locale.Format("app.ready.stdio", new Dictionary<string, object?> + { + ["protocol"] = info.ProtocolVersion, ["pid"] = info.ProcessId, ["logs"] = _logDirectory + }); + _application.Operational(message); + } + + public void HttpRequestStarted(McpHttpRequestStartInfo info) + { + if (_observedConnections.TryAdd(info.ConnectionId, 0)) + _application.Information($"HTTP connection observed connection={info.ConnectionId} remote={info.RemoteIp}:{info.RemotePort}"); + _application.Information($"HTTP request started connection={info.ConnectionId} trace={info.TraceId} remote={info.RemoteIp}:{info.RemotePort} method={info.Method} path={info.Path}"); + } + + public void HttpRequest(McpHttpRequestInfo info) + { + _application.Information(string.Create(CultureInfo.InvariantCulture, + $"HTTP request completed connection={info.ConnectionId} remote={info.RemoteIp}:{info.RemotePort} method={info.Method} path={info.Path} status={info.Status} duration_ms={info.DurationMs:F3}")); + _http?.WriteLine(JsonSerializer.Serialize(new + { + timestamp = info.Timestamp, + connection_id = info.ConnectionId, + trace_id = info.TraceId, + remote_ip = info.RemoteIp, + remote_port = info.RemotePort, + local_ip = info.LocalIp, + local_port = info.LocalPort, + method = info.Method, + path = info.Path, + status = info.Status, + duration_ms = info.DurationMs, + content_type = info.ContentType, + content_length = info.ContentLength, + user_agent = info.UserAgent, + mcp_protocol_version = NullIfEmpty(info.ProtocolVersion), + mcp_method = NullIfEmpty(info.McpMethod), + mcp_name = NullIfEmpty(info.McpName) + })); + } + + private static string? NullIfEmpty(string? value) => string.IsNullOrWhiteSpace(value) ? null : value; + public void Dispose() => _http?.Dispose(); +} diff --git a/src/Agent.App/Logging/RollingFileLog.cs b/src/Agent.App/Logging/RollingFileLog.cs index 801768d..8bdbbb4 100644 --- a/src/Agent.App/Logging/RollingFileLog.cs +++ b/src/Agent.App/Logging/RollingFileLog.cs @@ -4,52 +4,43 @@ namespace Agent.App.Logging; public sealed class RollingFileLog : IDisposable { - private readonly object _sync = new(); - private readonly string _path; - private readonly long _maxBytes; - private readonly int _retainedFiles; - private StreamWriter _writer; + private readonly RollingFileWriter _writer; + private readonly int _minimumLevel; - public RollingFileLog(string directory, long maxBytes, int retainedFiles) + public RollingFileLog(string directory, long maxBytes, int retainedFiles, string minimumLevel = "information") { Directory.CreateDirectory(directory); - _path = Path.Combine(directory, "application.log"); - _maxBytes = maxBytes; - _retainedFiles = retainedFiles; - _writer = Open(); + _writer = new RollingFileWriter(Path.Combine(directory, "application.log"), maxBytes, retainedFiles); + _minimumLevel = ParseLevel(minimumLevel); } public void Information(string message) => Write("INF", message); + public void Operational(string message) => Write("INF", message, force: true); + public void Warning(string message) => Write("WRN", message); public void Error(string message) => Write("ERR", message); + public void Fatal(string message) => Write("FTL", message); - private void Write(string level, string message) + private void Write(string level, string message, bool force = false) { - lock (_sync) - { - if (_writer.BaseStream.Length >= _maxBytes) Rotate(); - string line = string.Create(CultureInfo.InvariantCulture, $"{DateTimeOffset.UtcNow:O} [{level}] {message}"); - Console.Error.WriteLine(line); - _writer.WriteLine(line); - _writer.Flush(); - } + if (!force && Level(level) < _minimumLevel) return; + string line = string.Create(CultureInfo.InvariantCulture, $"{DateTimeOffset.UtcNow:O} [{level}] {message}"); + Console.Error.WriteLine(line); + _writer.WriteLine(line); } - private StreamWriter Open() => new(new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Read), new System.Text.UTF8Encoding(false)); - - private void Rotate() + private static int ParseLevel(string level) => level.ToLowerInvariant() switch { - _writer.Dispose(); - for (int index = _retainedFiles - 1; index >= 1; index--) - { - string source = $"{_path}.{index}"; - if (File.Exists(source)) File.Move(source, $"{_path}.{index + 1}", true); - } - if (File.Exists(_path)) File.Move(_path, $"{_path}.1", true); - _writer = Open(); - } + "information" or "info" => 0, + "warning" or "warn" => 1, + "error" => 2, + "fatal" => 3, + _ => throw new ArgumentException($"Unknown logging level '{level}'.", nameof(level)) + }; + + private static int Level(string level) => level switch { "INF" => 0, "WRN" => 1, "ERR" => 2, "FTL" => 3, _ => 0 }; public void Dispose() { - lock (_sync) _writer.Dispose(); + _writer.Dispose(); } } diff --git a/src/Agent.App/Logging/RollingFileWriter.cs b/src/Agent.App/Logging/RollingFileWriter.cs new file mode 100644 index 0000000..e155858 --- /dev/null +++ b/src/Agent.App/Logging/RollingFileWriter.cs @@ -0,0 +1,50 @@ +using System.Text; + +namespace Agent.App.Logging; + +internal sealed class RollingFileWriter : IDisposable +{ + private readonly object _sync = new(); + private readonly string _path; + private readonly long _maxBytes; + private readonly int _retainedFiles; + private StreamWriter _writer; + + public RollingFileWriter(string path, long maxBytes, int retainedFiles) + { + _path = path; + _maxBytes = maxBytes; + _retainedFiles = retainedFiles; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + _writer = Open(); + } + + public void WriteLine(string line) + { + lock (_sync) + { + if (_writer.BaseStream.Length >= _maxBytes) Rotate(); + _writer.WriteLine(line); + _writer.Flush(); + } + } + + private StreamWriter Open() => new(new FileStream(_path, FileMode.Append, FileAccess.Write, FileShare.Read), new UTF8Encoding(false)); + + private void Rotate() + { + _writer.Dispose(); + for (int index = _retainedFiles - 1; index >= 1; index--) + { + string source = $"{_path}.{index}"; + if (File.Exists(source)) File.Move(source, $"{_path}.{index + 1}", true); + } + if (File.Exists(_path)) File.Move(_path, $"{_path}.1", true); + _writer = Open(); + } + + public void Dispose() + { + lock (_sync) _writer.Dispose(); + } +} diff --git a/src/Agent.App/Program.cs b/src/Agent.App/Program.cs index 3fae93f..d9ee17a 100644 --- a/src/Agent.App/Program.cs +++ b/src/Agent.App/Program.cs @@ -35,7 +35,7 @@ internal static class Program string logDirectory = ConfigurationLoader.Resolve(baseDirectory, configuration.Logging.Directory); UserOnlyDirectory.Ensure(logDirectory); - using var log = new RollingFileLog(logDirectory, configuration.Logging.MaxFileBytes, configuration.Logging.RetainedFiles); + using var log = new RollingFileLog(logDirectory, configuration.Logging.MaxFileBytes, configuration.Logging.RetainedFiles, configuration.Logging.Level); if (commandLine.Command == AppCommand.Check) { WindowsPlatformCheckResult platform = WindowsPlatformCheck.Run(); @@ -57,8 +57,30 @@ internal static class Program } log.Information(locale.Get("app.starting")); + WindowsPlatformCheckResult servePlatform = WindowsPlatformCheck.Run(); + if (!servePlatform.Success) + { + string failure = locale.Format("app.preflight_failed", new Dictionary<string, object?> + { + ["operation"] = servePlatform.ErrorOperation ?? "privilege/BFE/WFP probe", + ["error_code"] = servePlatform.ErrorCode, + ["administrator"] = servePlatform.IsAdministrator.ToString().ToLowerInvariant(), + ["bfe"] = servePlatform.BfeEngineOpen.ToString().ToLowerInvariant(), + ["transaction"] = servePlatform.WfpWriteTransaction.ToString().ToLowerInvariant(), + ["filters"] = servePlatform.WfpFilterAddDelete.ToString().ToLowerInvariant() + }); + log.Fatal(failure); + return 2; + } + InternalToolDispatcher toolDispatcher = CreateToolDispatcher(configuration, baseDirectory, logDirectory); var runtimeObserver = new JsonLinesRuntimeObserver(logDirectory); + string taskStateDirectory = Path.Combine(baseDirectory, "state", "mcp-tasks"); + UserOnlyDirectory.Ensure(taskStateDirectory); + var taskStoreSettings = new McpTaskStoreSettings(taskStateDirectory, + TimeSpan.FromHours(configuration.Mcp.Tasks.TimeToLiveHours), configuration.Mcp.Tasks.PollIntervalMs); + using var hostObserver = new McpHostLogObserver(log, locale, logDirectory, configuration.Logging.HttpRequests, + configuration.Logging.MaxFileBytes, configuration.Logging.RetainedFiles); if (configuration.Mcp.Transport == "stdio") { string userPrompt = File.ReadAllText(ConfigurationLoader.Resolve(baseDirectory, configuration.Agent.UserSystemPrompt)); @@ -66,7 +88,8 @@ internal static class Program string[] skills = Directory.EnumerateFiles(skillDirectory, "*.md", SearchOption.TopDirectoryOnly).Select(File.ReadAllText).ToArray(); var runtimeSettings = new AgentRuntimeSettings(userPrompt, language, skills, "Windows AppContainer, ACL, Job Object, child-process restriction, and WFP sandbox capabilities.", configuration.Agent.MaxIterations, configuration.Agent.SameFailureLimit, locale.Get("ollama.vision_unsupported")); var visionLimits = new VisionLimits(configuration.Mcp.Images.MaxCount, configuration.Mcp.Images.MaxBytesEach, configuration.Mcp.Images.MaxTotalBytes); - await McpHost.RunStdioAsync(locale, OllamaSettingsFactory.Create(configuration.Ollama), runtimeSettings, visionLimits, CancellationToken.None, toolDispatcher, runtimeObserver).ConfigureAwait(false); + await McpHost.RunStdioAsync(locale, OllamaSettingsFactory.Create(configuration.Ollama), runtimeSettings, visionLimits, CancellationToken.None, + toolDispatcher, runtimeObserver, taskStoreSettings, hostObserver).ConfigureAwait(false); return 0; } if (configuration.Mcp.Transport == "http") @@ -77,7 +100,8 @@ internal static class Program var runtimeSettings = new AgentRuntimeSettings(userPrompt, language, skills, "Windows AppContainer, ACL, Job Object, child-process restriction, and WFP sandbox capabilities.", configuration.Agent.MaxIterations, configuration.Agent.SameFailureLimit, locale.Get("ollama.vision_unsupported")); var visionLimits = new VisionLimits(configuration.Mcp.Images.MaxCount, configuration.Mcp.Images.MaxBytesEach, configuration.Mcp.Images.MaxTotalBytes); await McpHost.RunHttpAsync(locale, OllamaSettingsFactory.Create(configuration.Ollama), runtimeSettings, visionLimits, - configuration.Mcp.Http.Host, configuration.Mcp.Http.Port, CancellationToken.None, toolDispatcher, runtimeObserver).ConfigureAwait(false); + configuration.Mcp.Http.Host, configuration.Mcp.Http.Port, CancellationToken.None, toolDispatcher, runtimeObserver, + taskStoreSettings, hostObserver).ConfigureAwait(false); return 0; } throw new ConfigurationException("Unsupported MCP transport."); |
