Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/Exceptionless.Web/Assistant/AssistantService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Web;
using Exceptionless.Core;
Expand Down Expand Up @@ -40,7 +41,15 @@ public sealed partial class AssistantService(
private const string SnoozeStackTool = "snooze_stack";
private const string UpdateSavedViewTool = "update_saved_view";
private const string UpdateStackStatusTool = "update_stack_status";
private static readonly JsonSerializerOptions s_jsonOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web).ConfigureExceptionlessApiDefaults();
private static readonly JsonSerializerOptions s_jsonOptions = CreateJsonOptions();

private static JsonSerializerOptions CreateJsonOptions()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web).ConfigureExceptionlessApiDefaults();
// Exie reads the same tool results as MCP clients, so its dates need the same UTC marker.
options.TypeInfoResolver = options.TypeInfoResolver!.WithAddedModifier(McpJsonSerializerOptions.WriteDatesAsUtc);
return options;
}

public IAsyncEnumerable<AssistantStreamEvent> StreamAsync(
AssistantChatRequest request,
Expand Down
21 changes: 13 additions & 8 deletions src/Exceptionless.Web/Mcp/ExceptionlessMcpTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public sealed partial class ExceptionlessMcpTools
private const string TimeZoneDescription = "Optional IANA time zone, such as America/Chicago, that time is resolved in, so now/d is the user's midnight. Defaults to UTC.";
private const string EventGroupByDescription = "Optional dimension to group counts by. Supported values: environment, version, type, source, status, tag, stack, user, level, error.type, error.code, os, os.version, browser. Multi-value fields such as tag, error.type, and error.code can place one event into multiple groups, so group totals may sum higher than the overall event total.";
private const string SnoozeDurationDescription = "Optional relative snooze duration such as 2h, 3d, or 1w. Do not combine with snoozeUntilUtc.";
private const string ProjectFilterDescription = "Optional Exceptionless filter expression applied to projects. Supported fields: id, name, organization_id, created_utc, updated_utc, last_event_date_utc.";
private const string ProjectFilterDescription = "Optional Exceptionless filter expression applied to projects. Supported fields: id, name, organization_id, created_utc, updated_utc, last_event_date_utc. name matches whole words, such as name:web, or word prefixes, such as name:web*; leading wildcards such as name:*web* are not supported.";
private const string StackFilterDescription = "Optional Exceptionless filter expression. Supported fields include: stack, project, project_id, organization, organization_id, type, status, title, description, tag, tags, references, fixed, hidden, regressed, error, first, first_occurrence, last, last_occurrence, occurrences, total_occurrences.";
private const string EventFilterDescription = "Optional Exceptionless filter expression applied to events. Supported fields include: id, project, project_id, stack, stack_id, organization, organization_id, type, environment, source, message, date, tag, tags, user, user.name, user.email, path, error, error.type, error.message, error.code, status, data.*. data.* works for custom data values that were indexed for search; arbitrary event detail data is returned by get_event but is not searchable unless indexed.";

Expand Down Expand Up @@ -1143,9 +1143,9 @@ private static SearchValidationResult ValidateProjectSearch(string? filter, stri
if (!TryValidateSort(sort, ProjectSortFields, out string? sortError))
return SearchValidationResult.Failed(McpErrors.InvalidSort(sortError ?? "Invalid sort.", sort, ProjectSortFields));

var filterFieldError = GetFilterFieldError(filter, ProjectFilterFields, allowIndexedDataFields: false);
if (filterFieldError is not null)
return SearchValidationResult.Failed(filterFieldError);
var filterError = GetLeadingWildcardError(filter) ?? GetFilterFieldError(filter, ProjectFilterFields, allowIndexedDataFields: false);
if (filterError is not null)
return SearchValidationResult.Failed(filterError);

return new SearchValidationResult(resolvedLimit, warning);
}
Expand Down Expand Up @@ -1183,11 +1183,16 @@ private async Task<SearchValidationResult> ValidateSearchAsync(
if (!queryValidation.IsValid)
return McpErrors.InvalidFilter($"Invalid filter: {queryValidation.Message ?? "Unable to parse filter."}");

// Elasticsearch rejects leading wildcards, which would otherwise fail the whole search.
if (filter is not null && s_leadingWildcardPattern.IsMatch(filter))
return McpErrors.InvalidFilter("Invalid filter: leading wildcards such as *timeout* are not supported. Search for a whole word instead, such as title:timeout or timeout.");
return GetLeadingWildcardError(filter);
}

return null;
/// <summary>Elasticsearch rejects leading wildcards, which would otherwise fail the whole search.</summary>
private static McpErrorInfo? GetLeadingWildcardError(string? filter)
{
if (filter is null || !s_leadingWildcardPattern.IsMatch(filter))
return null;

return McpErrors.InvalidFilter("Invalid filter: leading wildcards such as *timeout* are not supported. Search for a whole word or a word prefix instead, such as title:timeout or title:time*.");
}

private static bool TryValidateSort(string? sort, IReadOnlySet<string> allowedSortFields, out string? error)
Expand Down
54 changes: 54 additions & 0 deletions src/Exceptionless.Web/Mcp/McpJsonSerializerOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using ModelContextProtocol;

namespace Exceptionless.Web.Mcp;

/// <summary>
/// Serializer options for MCP tool output.
/// </summary>
public static class McpJsonSerializerOptions
{
public static JsonSerializerOptions Default { get; } = Create();

private static JsonSerializerOptions Create()
{
var options = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions);
options.TypeInfoResolver = options.TypeInfoResolver!.WithAddedModifier(WriteDatesAsUtc);
options.MakeReadOnly();
return options;
}

/// <summary>
/// Writes every <see cref="DateTime"/> property as UTC so it carries a Z, as the output schema's date-time format
/// (RFC 3339) requires. Older documents were stored without a time zone and read back as
/// <see cref="DateTimeKind.Unspecified"/>; every stored date is UTC. Changing the getter instead of adding a
/// converter keeps the generated output schema's date-time format.
/// </summary>
public static void WriteDatesAsUtc(JsonTypeInfo typeInfo)
{
if (typeInfo.Kind != JsonTypeInfoKind.Object)
return;

foreach (var property in typeInfo.Properties)
{
if (property.Get is not { } get)
continue;

if (property.PropertyType == typeof(DateTime))
property.Get = obj => ToUtc((DateTime)get(obj)!);
else if (property.PropertyType == typeof(DateTime?))
property.Get = obj => get(obj) is DateTime value ? ToUtc(value) : null;
}
}

private static DateTime ToUtc(DateTime value)
{
return value.Kind switch
{
DateTimeKind.Utc => value,
DateTimeKind.Local => value.ToUniversalTime(),
_ => DateTime.SpecifyKind(value, DateTimeKind.Utc)
};
}
}
3 changes: 1 addition & 2 deletions src/Exceptionless.Web/Mcp/McpToolResultFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ namespace Exceptionless.Web.Mcp;

public static class McpToolResultFilter
{
private static readonly JsonSerializerOptions s_jsonOptions = new(JsonSerializerDefaults.Web);
private static readonly string[] s_removedTimeArguments = ["last", "startUtc", "endUtc"];

public static CallToolResult MarkStructuredErrors(CallToolResult result)
Expand Down Expand Up @@ -40,7 +39,7 @@ public static CallToolResult MarkStructuredErrors(CallToolResult result)
message += " Pass a time range in time instead, using date math such as [now-24h TO now] or [now/d TO now/d] for today.";

var response = McpResponse<object>.Failed(McpErrors.InvalidArgument(message, unknown, allowed));
var structuredContent = JsonSerializer.SerializeToElement(response, s_jsonOptions);
var structuredContent = JsonSerializer.SerializeToElement(response, McpJsonSerializerOptions.Default);
return new CallToolResult
{
Content = [new TextContentBlock { Text = structuredContent.GetRawText() }],
Expand Down
2 changes: 1 addition & 1 deletion src/Exceptionless.Web/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ public static async Task<int> Main(string[] args)
builder.Services.AddMcpServer(options =>
options.ServerInstructions = "Exceptionless MCP tools are stateless. Direct get and stack-update tools accept a globally unique eventId or stackId without projectId; an explicitly supplied projectId is validated against that resource. Search and other scoped tools may omit scope only when the current OAuth grant exposes exactly one matching organization or project; otherwise use list_organizations, list_projects, or resolve_project and pass the required id explicitly. Previous tool calls never change the scope of later calls.")
.WithHttpTransport()
.WithTools<ExceptionlessMcpTools>()
.WithTools<ExceptionlessMcpTools>(McpJsonSerializerOptions.Default)
.WithRequestFilters(filters => filters.AddCallToolFilter(next => async (context, cancellationToken) =>
{
if (context.MatchedPrimitive is McpServerTool tool
Expand Down
65 changes: 65 additions & 0 deletions tests/Exceptionless.Tests/Mcp/ExceptionlessMcpToolsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,71 @@ public async Task ListProjectsAsync_MalformedFilter_ReturnsSpecificError()
Assert.Null(result.Data);
}

[Fact]
public async Task ListProjectsAsync_DatesStoredWithoutTimeZone_SerializeAsUtc()
{
// Arrange
var project = await _projectRepository.AddAsync(new Project
{
Comment thread
ejsmith marked this conversation as resolved.
Resolved
OrganizationId = TestConstants.OrganizationId,
Name = "Legacy Dates",
NextSummaryEndOfDayTicks = TimeProvider.GetUtcNow().UtcDateTime.Date.AddDays(1).Ticks,
CreatedUtc = new DateTime(2016, 1, 11, 20, 5, 59, 718, DateTimeKind.Unspecified),
LastEventDateUtc = new DateTime(2024, 12, 13, 14, 10, 26, DateTimeKind.Unspecified)
}, o => o.ImmediateConsistency());
var tools = await CreateToolsAsync(AuthorizationRoles.McpRead, AuthorizationRoles.ProjectsRead);

// Act
var stored = await _projectRepository.GetByIdAsync(project.Id);

// Assert
Assert.Equal(DateTimeKind.Unspecified, stored!.CreatedUtc.Kind);

// Act
var result = await tools.ListProjectsAsync(TestConstants.OrganizationId, sort: "created_utc", limit: 50);
var json = JsonSerializer.SerializeToElement(result, McpJsonSerializerOptions.Default);

// Assert
Assert.True(result.Ok);
var legacy = json.GetProperty("data").GetProperty("items").EnumerateArray().Single(item => item.GetProperty("id").GetString() == project.Id);
Assert.Equal("2016-01-11T20:05:59.718Z", legacy.GetProperty("createdUtc").GetString());
Assert.Equal("2024-12-13T14:10:26Z", legacy.GetProperty("lastEventDateUtc").GetString());
McpDateAssert.AllDatesHaveTimeZone(json);
}

[Theory]
[InlineData("name:*web*")]
[InlineData("*pistol*")]
public async Task ListProjectsAsync_LeadingWildcardFilter_ReturnsInvalidFilter(string filter)
{
// Arrange
var tools = await CreateToolsAsync(AuthorizationRoles.McpRead, AuthorizationRoles.ProjectsRead);

// Act
var result = await tools.ListProjectsAsync(TestConstants.OrganizationId, filter: filter);

// Assert
Assert.False(result.Ok);
Assert.Equal(McpErrorCodes.InvalidFilter, result.Error?.Code);
Assert.Contains("leading wildcards", result.Error?.Message);
}

[Theory]
[InlineData("name:disint*")]
[InlineData("name:Disint*")]
public async Task ListProjectsAsync_TrailingWildcardNameFilter_ReturnsMatchingProjects(string filter)
{
// Arrange
var tools = await CreateToolsAsync(AuthorizationRoles.McpRead, AuthorizationRoles.ProjectsRead);

// Act
var result = await tools.ListProjectsAsync(TestConstants.OrganizationId, filter: filter, limit: 50);

// Assert
Assert.True(result.Ok, result.Error?.Message);
Assert.Contains(Items(result), project => project.Id == TestConstants.ProjectId);
}

[Theory]
[InlineData("bad-project-id")]
public async Task GetProjectAsync_InvalidId_ReturnsInvalidId(string projectId)
Expand Down
36 changes: 36 additions & 0 deletions tests/Exceptionless.Tests/Mcp/McpDateAssert.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Text.Json;
using System.Text.RegularExpressions;
using Xunit;

namespace Exceptionless.Tests.Mcp;

/// <summary>
/// Asserts MCP output dates satisfy JSON Schema's date-time format (RFC 3339), which requires a Z or an offset.
/// </summary>
internal static partial class McpDateAssert
{
public static void AllDatesHaveTimeZone(JsonElement element, string path = "$")
{
switch (element.ValueKind)
{
case JsonValueKind.Object:
foreach (var property in element.EnumerateObject())
AllDatesHaveTimeZone(property.Value, $"{path}.{property.Name}");
break;
case JsonValueKind.Array:
int index = 0;
foreach (var item in element.EnumerateArray())
AllDatesHaveTimeZone(item, $"{path}[{index++}]");
break;
case JsonValueKind.String when DateTimePattern().IsMatch(element.GetString()!):
Assert.True(TimeZonePattern().IsMatch(element.GetString()!), $"{path} has no time zone: {element.GetString()}");
break;
}
}

[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}")]
private static partial Regex DateTimePattern();

[GeneratedRegex(@"(Z|[+-]\d{2}:\d{2})$")]
private static partial Regex TimeZonePattern();
}
55 changes: 55 additions & 0 deletions tests/Exceptionless.Tests/Mcp/McpToolContractTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Text.Json;
using Exceptionless.Web.Mcp;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Server;
Expand Down Expand Up @@ -82,6 +83,60 @@ public void UpdateStackStatus_SchemaConstrainsAllowedStatuses()
Assert.Equal(["open", "fixed", "ignored", "discarded"], status.GetProperty("enum").EnumerateArray().Select(item => item.GetString()));
}

[Fact]
public void Serialize_DatesWithoutTimeZone_WritesUtc()
{
// Arrange
var unspecified = new DateTime(2016, 1, 11, 20, 5, 59, DateTimeKind.Unspecified);
var project = new McpProjectResult("project", "organization", "Legacy", unspecified, unspecified, "/api/v2/projects/project", LastEventDateUtc: unspecified);
var stack = new McpStackResult("stack", "organization", "project", "error", "fixed", "Title", 1, unspecified, unspecified, [], [], false, unspecified, unspecified, "/api/v2/stacks/stack",
DateFixed: unspecified, SnoozeUntilUtc: unspecified);
var evt = new McpEventResult("event", "organization", "project", "stack", new DateTimeOffset(2016, 1, 11, 20, 5, 59, TimeSpan.FromHours(-5)), [], false, unspecified, "/api/v2/events/event");
var context = new McpContextResult("organization", "Org", "project", "Legacy", [], [project], false, false, unspecified);
var counts = new McpEventCountResult(1, 1, 1, 0, [], StartUtc: unspecified, EndUtc: unspecified, Groups: [new McpEventCountGroup("stack", 1, 1, [], FirstOccurrence: unspecified, LastOccurrence: unspecified)]);
var contextRequired = McpResponse<McpProjectResult>.Failed(McpErrors.ContextRequired("Select a project.", "project", [], [project]));
object[] results = [project, stack, evt, context, counts, contextRequired, McpResponse<McpListData<McpStackResult>>.Success(new McpListData<McpStackResult>([stack]))];

// Act
var serialized = results.Select(result => JsonSerializer.SerializeToElement(result, McpJsonSerializerOptions.Default)).ToArray();

// Assert
foreach (var json in serialized)
McpDateAssert.AllDatesHaveTimeZone(json);

Assert.Equal("2016-01-11T20:05:59Z", serialized[0].GetProperty("createdUtc").GetString());
}

[Fact]
public void Serialize_LocalAndUtcDates_WritesSameInstantInUtc()
{
// Arrange
var utc = new DateTime(2026, 6, 1, 12, 0, 0, DateTimeKind.Utc);
var project = new McpProjectResult("project", "organization", "Project", utc.ToLocalTime(), utc, "/api/v2/projects/project");

// Act
var json = JsonSerializer.SerializeToElement(project, McpJsonSerializerOptions.Default);

// Assert
Assert.Equal("2026-06-01T12:00:00Z", json.GetProperty("createdUtc").GetString());
Assert.Equal("2026-06-01T12:00:00Z", json.GetProperty("updatedUtc").GetString());
}

[Fact]
public void ListProjects_OutputSchemaAdvertisesDateTimeFormat()
{
// Arrange
var method = typeof(ExceptionlessMcpTools).GetMethod(nameof(ExceptionlessMcpTools.ListProjectsAsync))!;

// Act
var protocolTool = McpServerTool.Create(method, CreateMcpTools(), new McpServerToolCreateOptions { SerializerOptions = McpJsonSerializerOptions.Default }).ProtocolTool;
string schema = protocolTool.OutputSchema!.Value.GetRawText();

// Assert
Assert.Contains("\"createdUtc\"", schema, StringComparison.Ordinal);
Assert.Contains("\"date-time\"", schema, StringComparison.Ordinal);
}

private static ModelContextProtocol.Protocol.Tool CreateProtocolTool(string methodName)
{
var method = typeof(ExceptionlessMcpTools).GetMethod(methodName)
Expand Down
Loading